Writing a custom assertion for SharpTestEx
Actually SharpTestEx is my favorite way to make assertions in Unit testing. It has a lot of advantages, first of all it permits to write really clear assertions, then it works on the main Unit testing framework, so I can use the same assertion syntax for nunit and for MStest or MbUnit etc etc.
Another cool advantages is how simple is to extend the syntax, the IEnumerableConstraint has the Contain assertion to verify that an element is contained in a IEnumerable sequence of objects. Now I want to be able to write a ContainAny that accepts a lambda to specify a condition that must be satisfied by at least one of the elements of the collection.
The code is really simple, it is based on the Assertion<Source, Func> class that permits to send to the assertion engine an assertion that verify something. The third parameter of the Assertion constructor accepts a predicate that will be used to validate the assertion itself. In our example I use the Any linq method to verify that at least any of the element of the collection satisfy the original lambda.
now I want to verify that a list of uri does not contain any element with mail in the address
Simple and readable. In case of failure the error is.
Since this is really not so clear, I changed the assertion function a little bit.
The only difference is that now the function accepts an Expression tree, and uses Compile() method to create a real Function<T, Boolean> method used to search into the sequence. Now when the test fails it writes:
I really love SharpTestEx.