How to Unit Test methods that return FilterDefinition<BsonDocument>

I have service methods that I am using to dynamically return FilterDefinition<BsonDocument>. I am trying to write unit tests in C# to test that the correct FilterDefinitions are being returned. At runtime, the current unit test is returning a SimpleFilterDefinition<BsonDocument, int>. I thought to attempt to cast to that and if not null, check that the int value is as expected. But, I cannot cast to SimpleFilterDefinition due to its protection level. I did .ToBsonDocument(), but I am not seeing any values in it that would be helpful as far as checking that the field and values are as expected. What would be the suggested way to check that the field and value are as expected?

I was able to test this by creating the following private method:

private String ConvertFilterToJson(FilterDefinition<BsonDocument> filter)
    var serializerRegistry = MongoDB.Bson.Serialization.BsonSerializer.SerializerRegistry;
    var documentSerializer = serializerRegistry.GetSerializer<BsonDocument>();
    return filter.Render(documentSerializer, serializerRegistry).ToJson();

Then, in my unit test, I do:

Guid id = Guid.Empty;
var expectedFilter = Builders<BsonDocument>.Filter.Eq("Id", id);
var expectedJson = ConvertFilterToJson(expectedFilter);

var result = _mongoDbService.GetIdFilter(id);


var resultJson = ConvertFilterToJson(result);

Assert.Equal(expectedJson, resultJson);

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.