Introduction
Nunit’s Assert.That is a versatile assertion method.
It’s part of NUnit’s constraint-based assert model, which is more flexible and powerful than the traditional assert model. This approach allows for more readable and expressive test code.
Here’s a guide on how to use Assert.That effectively in different scenarios:
Basic Usage
The basic syntax of Assert.That is:
csharpCopy code
Assert.That(actual, constraint, message);
actualis the value being tested.constraintis the condition you expectactualto meet.messageis an optional parameter for a custom error message if the assertion fails.
Examples
1. Equality Check
int result = GetResultFromMethod();
Assert.That(result, Is.EqualTo(5), "The result should be 5.");2. Null Check
object myObject = GetObject();
Assert.That(myObject, Is.Null, "Object should be null.");3. Collection Checks
var collection = new List<int> { 1, 2, 3 };
Assert.That(collection, Has.Member(2), "Collection should contain the number 2.");4. String Checks
string message = "Hello, World!";
Assert.That(message, Does.Contain("World"), "Message should contain 'World'.");5. Type Checking
object myObject = GetObject();
Assert.That(myObject, Is.TypeOf<MyClass>(), "Object should be of type MyClass.");6. Exception Checking
TestDelegate action = () => myObject.SomeMethod();
Assert.That(action, Throws.TypeOf<InvalidOperationException>(), "Method should throw InvalidOperationException.");7. Property Checking
var person = new Person { Name = "John", Age = 30 };
Assert.That(person, Has.Property("Name").EqualTo("John"), "Person's name should be John.");Advanced Constraints
NUnit provides a range of constraints that can be used with Assert.That, making your tests more expressive and precise:
- Logical Constraints:
And,Or,Notfor combining conditions. - Range Constraints:
InRange,GreaterThan,LessThanfor numerical comparisons. - Collection Constraints:
All,Some,None,Exactlyfor detailed collection testing. - String Constraints:
StartsWith,EndsWith,Matches(for regex) for string testing.
Conclusion
NUnit’s Assert.That is a powerful part of the framework that allows for expressive and readable tests.
By leveraging the various constraints, you can create robust and comprehensive tests for your .NET applications.
Remember, the key to effective testing is not only to check for the expected outcomes but also to express your tests in a way that makes them easy to understand and maintain.
You can find the official NUnit documentation here: – https://docs.nunit.org.
I have written a number of other NUnit posts here: – NUnit’s Coolest Feature – Data-Driven Tests, Asynchronous Testing with NUnit and C#




