Debug.Assert vs Unit Testing Assert. class

I have quite complicated class and I wanted during debugging/testing to validate that the data in the class is consistent. So I created a method Validate and used it in unit testing class

MyComplexClass oClass= MyComplexClass.CreateClass();
Assert.IsTrue(Validate(oClass);

But then I understood, that it would be better to call this function in the code to ensure that validation happens in the application, not only in unit testing.
So I’ve added Validate method to the end of my  CreateClass() method like the following:

public MyComplexClass CreateClass()
{
  //code omitted
  Debug.Assert(Validate());

This approach is better, because it will work for every call. Also the method belongs to the same class and keeps a knowledge about the class in one place.

Note that there are different options depending how you are using unit test and how critical is validation you perform.
If you are going to use validation only during debugging and running unit tests for debug only, the Validate() method could be private.
If you run Unit Tests in Release mode(for continuous integration), it’s better to make the  Validate()  method public(or use unit test accessor approach to call private methods).
If the validation is important not only during debugging, but in production, you need to log validation errors or throw exception instead of simple  Debug.Assert(). In this case Validate should return not  just bool, but return failure message (or list of error messages).

So my recommendation is the following: If your unit tests methods have not-trivial code to validate results, consider to move it to Validate class method and call it inside the class functions, that create/manipulate the objects.

By the way, if you don’t want to see Debug.Assert messages during Unit Testing, add

When I wrote this post, I found the post with similar opinion- see Myths about Debug.Assert! post.

Advertisements