If you added custom serializers to your model, you almost certainly want to be able to unit test it. TDD is strongly encouraged here, simply because it is very easy to make mistakes. IBsonSeralizer
s themselves are not so easy to test and you can make a very legitimate argument they should be made internal
and not subject to unit testing. This is even more true if the serializers are complex and context dependent. Anyways, instead we are going to focus on unit testing the entire model which for our purposes is 'the unit'.
The most basic unit test we can write involves serializing and deserializing the model. Here we are going to use BsonExtensionMethods.ToJson
and BsonSerializer.Deserialize
. If the model doesn't involve any type overrides (using RegisterClassMap
) or custom value types (using BsonSerializer.RegisterSerializer
), then it is pretty safe to leave it there. The test will guard against future changes to the model which could cause production issues. MongoDB has got a lot of unit tests to ensure they can property serialize/deserialize objects and primitive types, but you are welcome to add asserations after the object is deserialized for extra peace of mind.
If however the model involves specialized behaviour then these tests become very useful as they can help you very precisely pin-point where something is failing. The catch is to remember to register serializers (either in [Setup] in Nunit or static constructor in xUnit).
1 2 3 4 5 6 7 8 9 10 11 12 |
//using MongoDB.Bson; //using MongoDB.Bson.Serialization; static MyTest() { RegisterSerializers(); } [Fact] public void CanSeralizeAndDeserializeCustomType() { var serializedModel = BsonExtensionMethods.ToJson(test); BsonSerializer.Deserialize<Type>(serializedModel); } |