Bob Tway
Bob Tway

Reputation: 9613

Unit testing a specific MongoDb FilterDefintion in C# with Moq

Trying to unit test the following MongoDb update function in C#.

var update = Builders<InvestorMongoDao>.Update
      .Set(x => x.EmailAddress, command.EmailAddress);

await this.myDatabase.Users
.UpdateOneAsync(x => x.UserId == userId), update)
.ConfigureAwait(false);

I can easily check whether this function is called with a generic filter:

this.mockCollection
    .Verify(x => x.UpdateOneAsync(It.IsAny<FilterDefinition<MyDao>>(), 
        It.IsAny<UpdateDefinition<MyDao>>(), 
        It.IsAny<UpdateOptions>(), 
        It.IsAny<CancellationToken>()));

However, I want to try and verify that it's being called with the expected parameter. I cannot seem to find a way to extract the parameter I want to check from FilterDefinition. I have tried this:

var foo = Builders<MyDao>.Filter.Eq("UserId", expectedUserId);
this.mockCollection
    .Verify(x => x.UpdateOneAsync(It.Is<FilterDefinition<MyDao>>(a => a == foo), 
        It.IsAny<UpdateDefinition<MyDao>>(), 
        It.IsAny<UpdateOptions>(), 
        It.IsAny<CancellationToken>()));

But the test states the invocation is not performed. What am I doing wrong?

Upvotes: 1

Views: 2211

Answers (1)

Bob Tway
Bob Tway

Reputation: 9613

It appears you can approximate what's needed here by using Render.

var serializerRegistry = BsonSerializer.SerializerRegistry;
var documentSerializer = serializerRegistry.GetSerializer<MyDao>();
var expectedFilter = Builders<MyDao>.Filter.Eq("UserId", existingInvestor2.InvestorId);

this.mockCollection
    .Verify(x => x.UpdateOneAsync(It.Is<FilterDefinition<MyDao>>(a => a.Render(documentSerializer, serializerRegistry) == expectedFilter.Render(documentSerializer, serializerRegistry)), 
        It.IsAny<UpdateDefinition<MyDao>>(), 
        It.IsAny<UpdateOptions>(), 
        It.IsAny<CancellationToken>()));

Upvotes: 2

Related Questions