Creating Custom NUnit Assertions
page 2 of 5
by Brian Mains
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 34018/ 88

New Assertions

The newest version of NUnit (at the time of this writing, 2.4.1) features some brand new assertion classes. There is the ability to compare collections with CollectionAssert, determining whether each item in a collection is unique, not null, are instances of a specific type, etc. The requirement for this class is that the collection implements ICollection (some of the collections in .NET 2.0 implement the generic version).

In addition to that, there is the StringAssert type that determines if one string contains another string, whether one string starts with a value, whether one string ends with a value, or if they are equal when case typing is ignored.  FileAssert determines whether two files do or do not match, using the file path or stream objects to do the comparison.

In addition, Assert.That uses contraints to perform the comparison of the values. To make it easier, NUnit contains SyntaxHelpers namespace with an Is, Has, List, or Text helpers that contain a series of properties that return constraint-based objects to perform constraint matching for you.  For instance, the following are several of the constraints that are possible.  If you use the reflector tool to look at the source code, you will see that this new method of performing comparisons, using constraints, is used a lot in the NUnit assertions.

Listing 1

Assert.That("My Text Value", Text.StartsWith("My"));
 Assert.That(objValue1, Is.EqualTo(objValue2));
Assert.That(objValue1, Is.SameAs(objValue2));

This article will show you how to create your own assertions with custom constraints. Creating custom assertions can be helpful to perform more advanced comparisons of the data in your project.

View Entire Article

User Comments

Title: NUnit Test Generator   
Name: Thinzar
Date: 2012-07-02 1:55:11 AM
I want to write NUnit Test generator tool. Pls tell me what features would be useful to add.
Title: NUnit Test Generator   
Name: Greg Finzer
Date: 2007-09-28 12:21:06 PM
Brian, Thanks for the great article. I recently created a tool to create NUnit Tests. What other features would be useful to add?

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2021  |  Page Processed at 2021-12-01 6:48:21 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search