Monday, June 9, 2014

[Visual C# - Unit Tests] How to extend NFluent and make it even more powerful

 

In my last article on NFluent I have shown you how it can help you to easily write clear and meaningful unit tests. In this article I am going to explain how you can extent NFluent by adding new custom validations.

What are DataAnnotations and how to use them ?

The System.ComponentModel.DataAnnotations namespace allows to define constraints on classes, methods and properties. DataAnnotations are often used within application based on ASP.NET MVC and Entity Framework for validation purposes.

The example below shows how to constrain user objects, with the following rules : All user objects have mandatory ID and Name properties, while the value of the ID property has to be in-between 1 and 999 and the Name property cannot exceed 30 characters.

image

DataAnnotations are widely used within the .NET Framework and I am happy to announce that NFluent uses them for extending its functionalities. So nothing new to learn for developers, who are already using them in their daily work!

Extend NFluent by adding new custom validations

It is very easy to add new custom validations to NFluent, you just have write an extension method and add the new custom verification code, as you can see in the following example implementation :

image

Note that a FluentCheckException is returned in case of validation errors.

How to use the custom validation in your code

Now that you have added your custom validation code, you can use it within your unit tests. You just have to call the DataAnnotationsAreValid() method :

image

Conclusion

This article has shown how easy it is to extent NFluent by adding custom validation code and then using it within your unit tests by just doing a single method call. There are obviously other ways to extend NFluent, but this simple and quick example is already sufficient for most scenarios.


Share/Save/Bookmark

No comments: