What Is NUnit? NUnit is a unit-testing framework for all .Net languages. Initially ported fromJUnit, the current productio...
Assertions are central to unit testing in any of the xUnit frameworks, and NUnit is no exception.NUnit provides a rich set...
Assert.AreEqual( double.NegativeInfinity, double.NegativeInfinity );           Assert.AreEqual( double.NaN, double.NaN );N...
Assert.IsFalse( bool condition);Assert.IsFalse( bool condition, string message );Assert.IsFalse( bool condition, string me...
Comparisons (NUnit 2.2.4)The following methods test whether one object is greater than than another. Contrary to thenormal...
language or mathematical order. Thus Assert.GreaterOrEqual( x, y ) asserts that x is greaterthan or equal to y ( x >= y )....
object[] parms );Assert.Less( uint arg1, uint arg2 );Assert.Less( uint arg1, uint arg2, string message );Assert.Less( uint...
object[] parms );Assert.LessOrEqual( ulong arg1, ulong arg2 );Assert.LessOrEqual( ulong arg1, ulong arg2, string message )...
Beginning with NUnit 2.5, generic equivalents are available in .NET 2.0 NUnit packages.Assert.IsInstanceOf<T>( object actu...
string message, params object[] parms);T Assert.Throws<T>( TestDelegate code );T Assert.Throws<T>( TestDelegate code, stri...
void MethodThatThrows()  {    throw new ArgumentException();  }This example shows use of the return value to perform addit...
// Allow any kind of exceptionAssert.Catch( code );         Utility Methods   1. Four utility methods, Pass(), Fail(), Ign...
32. The Assert.Inconclusive method indicates that the test could not be completed with the      data available. It should ...
70.   CollectionAssert.AllItemsAreInstancesOfType( IEnumerable collection,71.             Type expectedType, string messag...
120.           string message, params object[] args );   121.   122. CollectionAssert.IsSubsetOf( IEnumerable subset, IEnu...
FileAssert.AreEqual( FileInfo expected, FileInfo actual );FileAssert.AreEqual( FileInfo expected, FileInfo actual,        ...
string message, params object[] args );DirectoryAssert.AreNotEqual( DirectoryInfo expected,         DirectoryInfo actual )...
DirectoryAssert.IsNotWithin( DirectoryInfo expected,              DirectoryInfo actual );DirectoryAssert.IsNotWithin( Dire...
Assert.That( bool condition, string message, object[] parms );Assert.That( TestDelegate del, IResolveConstraint constraint...
SyntaxIs.EqualTo( object expected )Modifiers...IgnoreCase...AsCollection...NoClip...Within(object tolerance)      .Ulps   ...
Assert.That( double.NegativeInfinity, Is.EqualTo( double.NegativeInfinity ));Assert.That( double.NaN, Is.EqualTo( double.N...
int array2x2    = new int[,] { { 1, 2 } { 3, 4 } };int array4 =    new int[] { 1, 2, 3, 4 };Assert.That(    array2x2, Is.N...
5. When an equality test between two strings fails, the relevant portion of of both strings is      displayed in the error...
SyntaxIs.NullExamples of UseAssert.That( anObject, Is.Null );Assert.That( anObject, Is.Not.Null );TrueConstraintActionTest...
Assert.That( aDouble, Is.Not.NaN );EmptyConstraintActionTests that an object is an empty string, directory or collection.C...
Beginning with NUnit 2.5, you may supply your own comparison algorithm through the Usingmodifier.GreaterThanConstraintActi...
LessThanConstraintActionTests that one value is less than another.ConstructorLessThanConstraint(object expected)SyntaxIs.L...
RangeConstraintActionConstructorRangeConstraint(IComparable from, IComparable to)SyntaxIs.InRange(IComparable from, ICompa...
...RespectCaseExamples of UseAssert.That( "/folder1/./junk/../folder2",        Is.SamePath( "/folder1/folder2" ) );Assert....
InstanceOfTypeConstraint( TypeIs.InstanceOfType( Type )                                  tests that an object is an instan...
Assert.That( phrase, Is.StringContaining( "tests fail" ) );Assert.That( phrase, Contains.Substring( "tests fail" ) );Asser...
ConstructorEndsWithConstraint(string expected)SyntaxIs.StringEnding(string expected)EndsWith(string expected)[Obsolete] Te...
Notes   1. Matches may appear only in the body of a constraint expression or when the inherited syntax is      used.Collec...
ConstructorSomeItemsConstraint(Constraint itemConstraint)SyntaxHas.Some...Examples of Useint[] iarray = new int[] { 1, 2, ...
Notes   1. ??CollectionContainsConstraintActionTests that a collection contains an object.ConstructorCollectionContainsCon...
Notes   1. To compare collections for equality, use Is.EqualTo().CollectionSubsetConstraintActionTests that one collection...
Notes   1. Modifiers may be combined and may appear in any order. If the same modifier is used more      than once, the re...
Examples of Use// .NET 1.1Assert.That( new TestDelegate(SomeMethod),  Throws.TypeOf(typeof(ArgumentException)));Assert.Tha...
Tests that all members of a collection matchIs.All...            AllItemsConstraint( Constraint )                         ...
Normally, ListMapper will be used through the List.Map() syntax helper or the inherited syntaxequivalent, Map(). The follo...
resolved again by the second Assert.That(), which only sees the NullConstraint and not theNotConstraint.So, for reusabilit...
CategoryAttribute (NUnit 2.2)The Category attribute provides an alternative to suites for dealing with groups of tests. Ei...
namespace NUnitTests {  // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit...
#include "cppsample.h"namespace NUnitTests {  // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixtur...
MyTest(2, "A")        MyTest(2, "B")        MyTest(3, "A")        MyTest(3, "B")[Test, Combinatorial]public void MyTest(  ...
namespace NUnitTests{  [TestFixture]  [Culture("fr-FR")]  public __gc class FrenchCultureTests  {     // ...  };}#include ...
#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{  [TestFixture]  ...
Automatically Supplied DatapointsIt is normally not necessary to specify datapoints for boolean or enum arguments. Beginni...
namespace NUnitTests{  [TestFixture, Description("Fixture description here")]  public __gc class SomeTests  {     [Test, D...
Beginning with NUnit 2.2.4, it became possible to specify the type of exception as a string,avoiding the need for a refere...
...If MatchType is not specified, an exact match is used as before.Specifying a Custom Error MessageWith NUnit 2.4, it is ...
This technique may be used without implementing IExpectException or in combination with it.In the latter case, the designa...
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
What Do You Mean By NUnit
Upcoming SlideShare
Loading in...5
×

What Do You Mean By NUnit

1,327

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,327
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

What Do You Mean By NUnit

  1. 1. What Is NUnit? NUnit is a unit-testing framework for all .Net languages. Initially ported fromJUnit, the current production release, version 2.5, is the sixth major release of this xUnit basedunit testing tool for Microsoft .NET. It is written entirely in C# and has been completelyredesigned to take advantage of many .NET language features, for example custom attributes andother reflection related capabilities. NUnit brings xUnit to all .NET languages.Definition • NUnit is an automated unit-testing framework for all .Net languages.• Initially ported from JUnit, which is a unit testing framework for Java applications.• It is written entirely in C# and has been completely redesigned to take advantage of many .NETlanguage features.• NUnit brings xUnit to all test are written in .NET supported language e.g. C#, VC, VB.NET, J#etc.• NUnit is an open source free to use with your .NET projects.• NUnit provides a class library which includes some classes, features and methods to help youwrite test scripts.• NUnit provides user interface application to execute the test scripts and displays result• NUnit does not create any test scripts by itself. We have to write test scripts and use NUnittools and classes to make the unit testing easier and display the result as a success or failure. Features of NUnit • Assertions• Attributes 1. Assertions Definition Assertions are central to unit testing in any of the xUnit frameworks,and NUnit is no exception. NUnit provides a rich set of assertions as static methods of the Assertclass.The most commonly used assertions.• Equality Asserts ,• Identity Asserts • Comparison Asserts • Type Asserts• Condition tests,• Utility methods,• StringAssert,• CollectionAssert,• FileAssert• Equal Constraint (Available NUnit 2.4)• Same As Constraint (Available NUnit 2.4)• Condition Constraints (Available NUnit 2.4) • Comparison Constraints (Available NUnit 2.4)• Type Constraints (Available NUnit 2.4)• String Constraints (Available NUnit 2.4)• Collection Constraints (Available NUnit 2.4)• Compound Constraints (Available NUnit 2.4)• Custom Constraints (Available NUnit 2.4) 2. Attributes • Category • Description • Expected Exception • Explicit • Ignore • Platform • Property• SetUp • SetUpFixture • Suite • TearDown • Test • TestFixture • TestFixtureSetUp• TestFixtureTearDownAdd References in Project Browse references from C:Program FilesNUnit2.5.2binnet-2.0framework i.e. nunit.framework.dllAssertions
  2. 2. Assertions are central to unit testing in any of the xUnit frameworks, and NUnit is no exception.NUnit provides a rich set of assertions as static methods of the Assert class.If an assertion fails, the method call does not return and an error is reported. If a test containsmultiple assertions, any that follow the one that failed will not be executed. For this reason, itsusually best to try for one assertion per test.Each method may be called without a message, with a simple text message or with a messageand arguments. In the last case the message is formatted using the provided text and arguments.Two ModelsBefore NUnit 2.4, a separate method of the Assert class was used for each different assertion.We call this the "Classic Model." It continues to be supported in NUnit, since many peopleprefer it.Beginning with NUnit 2.4, a new "Constraint-based" model was introduced. This approach usesa single method of the Assert class for all assertions, passing a Constraint object that specifiesthe test to be performed.This constraint-based model is now used internally by NUnit for all assertions. The methods ofthe classic approach have been re-implemented on top of this new model.Equality AssertsThese methods test whether the two arguments are equal. Overloaded methods are provided forcommon value types so that languages that dont automatically box values can use them directly.Comparing Numerics of Different TypesThe method overloads that compare two objects make special provision so that numeric values ofdifferent types compare as expected. This assert succeeds: Assert.AreEqual( 5, 5.0 );Comparing Floating Point ValuesValues of type float and double are normally compared using an additional argument thatindicates a tolerance within which they will be considered as equal. Beginning with NUnit 2.4.4,the value of GlobalSettings.DefaultFloatingPointTolerance is used if a third argument is notprovided. In earlier versions, or if the default has not been set, values are tested for exactequality.Special values are handled so that the following Asserts succeed: Assert.AreEqual ( double.PositiveInfinity, double.PositiveInfinity );
  3. 3. Assert.AreEqual( double.NegativeInfinity, double.NegativeInfinity ); Assert.AreEqual( double.NaN, double.NaN );Note: The last example above represents a change with NUnit 2.2.3. In earlier releases, the test wouldfail. We have made this change because the new behavior seems to be more useful in tests. To avoidconfusion, we suggest using the new Assert.IsNaN method where appropriate.Comparing Arrays and CollectionsSince version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginningwith version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections maybe compared. Two arrays or collections will be treated as equal by Assert.AreEqual if they havethe same dimensions and if each of the corresponding elements is equal.Identity AssertsAssert.AreSame and Assert.AreNotSame test whether the same objects are referenced by thetwo arguments.Assert.AreSame( object expected, object actual );Assert.AreSame( object expected, object actual, string message );Assert.AreSame( object expected, object actual, string message, params object[] parms );Assert.AreNotSame( object expected, object actual );Assert.AreNotSame( object expected, object actual, string message );Assert.AreNotSame( object expected, object actual, string message, params object[] parms );Assert.Contains is used to test whether an object is contained in an array or list.Assert.Contains( object anObject, IList collection );Assert.Contains( object anObject, IList collection, string message );Assert.Contains( object anObject, IList collection, string message, params object[] parms );Condition AssertsMethods that test a specific condition are named for the condition they test and take the valuetested as their first argument and, optionally a message as the second. The following methods areprovided:Assert.IsTrue( bool condition );Assert.IsTrue( bool condition, string message );Assert.IsTrue( bool condition, string message, object[] parms );Assert.True( bool condition );Assert.True( bool condition, string message );Assert.True( bool condition, string message, object[] parms );
  4. 4. Assert.IsFalse( bool condition);Assert.IsFalse( bool condition, string message );Assert.IsFalse( bool condition, string message, object[] parms );Assert.False( bool condition);Assert.False( bool condition, string message );Assert.False( bool condition, string message, object[] parms );Assert.IsNull( object anObject );Assert.IsNull( object anObject, string message );Assert.IsNull( object anObject, string message, object[] parms );Assert.Null( object anObject );Assert.Null( object anObject, string message );Assert.Null( object anObject, string message, object[] parms );Assert.IsNotNull( object anObject );Assert.IsNotNull( object anObject, string message );Assert.IsNotNull( object anObject, string message, object[] parms );Assert.NotNull( object anObject );Assert.NotNull( object anObject, string message );Assert.NotNull( object anObject, string message, object[] parms );Assert.IsNaN( double aDouble );Assert.IsNaN( double aDouble, string message );Assert.IsNaN( double aDouble, string message, object[] parms );Assert.IsEmpty( string aString );Assert.IsEmpty( string aString, string message );Assert.IsEmpty( string aString, string message, params object[] args );Assert.IsNotEmpty( string aString );Assert.IsNotEmpty( string aString, string message );Assert.IsNotEmpty( string aString, string message, params object[] args );Assert.IsEmpty( ICollection collection );Assert.IsEmpty( ICollection collection, string message );Assert.IsEmpty( ICollection collection, string message, params object[] args );Assert.IsNotEmpty( ICollection collection );Assert.IsNotEmpty( ICollection collection, string message );Assert.IsNotEmpty( ICollection collection, string message, params object[] args );Two forms are provided for the True, False, Null and NotNull conditions. The "Is" forms arecompatible with earlier versions of the NUnit framework, while those without "Is" are providedfor compatibility with NUnitLite.Assert.IsEmpty and Assert.IsNotEmpty may be used to test either a string or a collection.
  5. 5. Comparisons (NUnit 2.2.4)The following methods test whether one object is greater than than another. Contrary to thenormal order of Asserts, these methods are designed to be read in the "natural" English-languageor mathematical order. Thus Assert.Greater( x, y ) asserts that x is greater than y ( x > y ).Assert.Greater( int arg1, int arg2 );Assert.Greater( int arg1, int arg2, string message );Assert.Greater( int arg1, int arg2, string message, object[] parms );Assert.Greater( uint arg1, uint arg2 );Assert.Greater( uint arg1, uint arg2, string message );Assert.Greater( uint arg1, uint arg2, string message, object[] parms );Assert.Greater( long arg1, long arg2 );Assert.Greater( long arg1, long arg2, string message );Assert.Greater( long arg1, long arg2, string message, object[] parms );Assert.Greater( ulong arg1, ulong arg2 );Assert.Greater( ulong arg1, ulong arg2, string message );Assert.Greater( ulong arg1, ulong arg2, string message, object[] parms );Assert.Greater( decimal arg1, decimal arg2 );Assert.Greater( decimal arg1, decimal arg2, string message );Assert.Greater( decimal arg1, decimal arg2, string message, object[] parms );Assert.Greater( double arg1, double arg2 );Assert.Greater( double arg1, double arg2, string message );Assert.Greater( double arg1, double arg2, string message, object[] parms );Assert.Greater( double arg1, double arg2 );Assert.Greater( double arg1, double arg2, string message );Assert.Greater( double arg1, double arg2, string message, object[] parms );Assert.Greater( float arg1, float arg2 );Assert.Greater( float arg1, float arg2, string message );Assert.Greater( float arg1, float arg2, string message, object[] parms );Assert.Greater( IComparable arg1, IComparable arg2 );Assert.Greater( IComparable arg1, IComparable arg2, string message );Assert.Greater( IComparable arg1, IComparable arg2, string message, object[] parms );The following methods test whether one object is greater than or equal to another. Contrary tothe normal order of Asserts, these methods are designed to be read in the "natural" English-
  6. 6. language or mathematical order. Thus Assert.GreaterOrEqual( x, y ) asserts that x is greaterthan or equal to y ( x >= y ).Assert.GreaterOrEqual( int arg1, int arg2 );Assert.GreaterOrEqual( int arg1, int arg2, string message );Assert.GreaterOrEqual( int arg1, int arg2, string message, object[] parms );Assert.GreaterOrEqual( uint arg1, uint arg2 );Assert.GreaterOrEqual( uint arg1, uint arg2, string message );Assert.GreaterOrEqual( uint arg1, uint arg2, string message, object[] parms );Assert.GreaterOrEqual( long arg1, long arg2 );Assert.GreaterOrEqual( long arg1, long arg2, string message );Assert.GreaterOrEqual( long arg1, long arg2, string message, object[] parms );Assert.GreaterOrEqual( ulong arg1, ulong arg2 );Assert.GreaterOrEqual( ulong arg1, ulong arg2, string message );Assert.GreaterOrEqual( ulong arg1, ulong arg2, string message, object[] parms );Assert.GreaterOrEqual( decimal arg1, decimal arg2 );Assert.GreaterOrEqual( decimal arg1, decimal arg2, string message );Assert.GreaterOrEqual( decimal arg1, decimal arg2, string message, object[] parms );Assert.GreaterOrEqual( double arg1, double arg2 );Assert.GreaterOrEqual( double arg1, double arg2, string message );Assert.GreaterOrEqual( double arg1, double arg2, string message, object[] parms );Assert.GreaterOrEqual( double arg1, double arg2 );Assert.GreaterOrEqual( double arg1, double arg2, string message );Assert.GreaterOrEqual( double arg1, double arg2, string message, object[] parms );Assert.GreaterOrEqual( float arg1, float arg2 );Assert.GreaterOrEqual( float arg1, float arg2, string message );Assert.GreaterOrEqual( float arg1, float arg2, string message, object[] parms );Assert.GreaterOrEqual( IComparable arg1, IComparable arg2 );Assert.GreaterOrEqual( IComparable arg1, IComparable arg2, string message );Assert.GreaterOrEqual( IComparable arg1, IComparable arg2, string message, object[] parms );The following methods test whether one object is less than than another. Contrary to the normalorder of Asserts, these methods are designed to be read in the "natural" English-language ormathematical order. Thus Assert.Less( x, y ) asserts that x is less than y ( x < y ).Assert.Less( int arg1, int arg2 );Assert.Less( int arg1, int arg2, string message );Assert.Less( int arg1, int arg2, string message,
  7. 7. object[] parms );Assert.Less( uint arg1, uint arg2 );Assert.Less( uint arg1, uint arg2, string message );Assert.Less( uint arg1, uint arg2, string message, object[] parms );Assert.Less( long arg1, long arg2 );Assert.Less( long arg1, long arg2, string message );Assert.Less( long arg1, long arg2, string message, object[] parms );Assert.Less( ulong arg1, ulong arg2 );Assert.Less( ulong arg1, ulong arg2, string message );Assert.Less( ulong arg1, ulong arg2, string message, object[] parms );Assert.Less( decimal arg1, decimal arg2 );Assert.Less( decimal arg1, decimal arg2, string message );Assert.Less( decimal arg1, decimal arg2, string message, object[] parms );Assert.Less( double arg1, double arg2 );Assert.Less( double arg1, double arg2, string message );Assert.Less( double arg1, double arg2, string message, object[] parms );Assert.Less( float arg1, float arg2 );Assert.Less( float arg1, float arg2, string message );Assert.Less( float arg1, float arg2, string message, object[] parms );Assert.Less( IComparable arg1, IComparable arg2 );Assert.Less( IComparable arg1, IComparable arg2, string message );Assert.Less( IComparable arg1, IComparable arg2, string message, object[] parms );The following methods test whether one object is less than or equal to another. Contrary to thenormal order of Asserts, these methods are designed to be read in the "natural" English-languageor mathematical order. Thus Assert.LessOrEqual( x, y ) asserts that x is less than or equal to y (x <= y ).Assert.LessOrEqual( int arg1, int arg2 );Assert.LessOrEqual( int arg1, int arg2, string message );Assert.LessOrEqual( int arg1, int arg2, string message, object[] parms );Assert.LessOrEqual( uint arg1, uint arg2 );Assert.LessOrEqual( uint arg1, uint arg2, string message );Assert.LessOrEqual( uint arg1, uint arg2, string message, object[] parms );Assert.LessOrEqual( long arg1, long arg2 );Assert.LessOrEqual( long arg1, long arg2, string message );Assert.LessOrEqual( long arg1, long arg2, string message,
  8. 8. object[] parms );Assert.LessOrEqual( ulong arg1, ulong arg2 );Assert.LessOrEqual( ulong arg1, ulong arg2, string message );Assert.LessOrEqual( ulong arg1, ulong arg2, string message, object[] parms );Assert.LessOrEqual( decimal arg1, decimal arg2 );Assert.LessOrEqual( decimal arg1, decimal arg2, string message );Assert.LessOrEqual( decimal arg1, decimal arg2, string message, object[] parms );Assert.LessOrEqual( double arg1, double arg2 );Assert.LessOrEqual( double arg1, double arg2, string message );Assert.LessOrEqual( double arg1, double arg2, string message, object[] parms );Assert.LessOrEqual( float arg1, float arg2 );Assert.LessOrEqual( float arg1, float arg2, string message );Assert.LessOrEqual( float arg1, float arg2, string message, object[] parms );Assert.LessOrEqual( IComparable arg1, IComparable arg2 );Assert.LessOrEqual( IComparable arg1, IComparable arg2, string message );Assert.LessOrEqual( IComparable arg1, IComparable arg2, string message, object[] parms );Type Asserts (NUnit 2.2.3 / 2.5)These methods allow us to make assertions about the type of an object.Assert.IsInstanceOfType( Type expected, object actual );Assert.IsInstanceOfType( Type expected, object actual, string message );Assert.IsInstanceOfType( Type expected, object actual, string message, params object[] parms );Assert.IsNotInstanceOfType( Type expected, object actual );Assert.IsNotInstanceOfType( Type expected, object actual, string message );Assert.IsNotInstanceOfType( Type expected, object actual, string message, params object[] parms );Assert.IsAssignableFrom( Type expected, object actual );Assert.IsAssignableFrom( Type expected, object actual, string message );Assert.IsAssignableFrom( Type expected, object actual, string message, params object[] parms );Assert.IsNotAssignableFrom( Type expected, object actual );Assert.IsNotAssignableFrom( Type expected, object actual, string message );Assert.IsNotAssignableFrom( Type expected, object actual, string message, params object[] parms );
  9. 9. Beginning with NUnit 2.5, generic equivalents are available in .NET 2.0 NUnit packages.Assert.IsInstanceOf<T>( object actual );Assert.IsInstanceOf<T>( object actual, string message );Assert.IsInstanceOf<T>( object actual, string message, params object[] parms );Assert.IsNotInstanceOf<T>( object actual );Assert.IsNotInstanceOf<T>( object actual, string message );Assert.IsNotInstanceOf<T>( object actual, string message, params object[] parms );Assert.IsAssignableFrom<T>( object actual );Assert.IsAssignableFrom<T>( object actual, string message );Assert.IsAssignableFrom<T>( object actual, string message, params object[] parms );Assert.IsNotAssignableFrom<T>( object actual );Assert.IsNotAssignableFrom<T>( object actual, string message );Assert.IsNotAssignableFrom<T>( object actual, string message, params object[] parms );Exception Asserts (NUnit 2.5)The Assert.Throws method is pretty much in a class by itself. Rather than comparing values, itattempts to invoke a code snippet, represented as a delegate, in order to verify that it throws aparticular exception.Its also in a class by itself in that it returns an Exception, rather than void, if the Assert issuccessful. See the example below for a few ways to use this.Assert.Throws may be used with a constraint argument, which is applied to the actual exceptionthrown, or with the Type of exception expected. The Type format is available in both both a non-generic and (in the .NET 2.0 version) generic form.Assert.DoesNotThrow simply verifies that the delegate does not throw an exception.Assert.Catch is similar to Assert.Throws but will pass for an exception that is derived from theone specified.Exception Assert.Throws( Type expectedExceptionType, TestDelegate code );Exception Assert.Throws( Type expectedExceptionType, TestDelegate code, string message );Exception Assert.Throws( Type expectedExceptionType, TestDelegate code, string message, params object[] parms);Exception Assert.Throws( IResolveConstraint constraint, TestDelegate code );Exception Assert.Throws( IResolveConstraint constraint, TestDelegate code, string message );Exception Assert.Throws( IResolveConstraint constraint, TestDelegate code,
  10. 10. string message, params object[] parms);T Assert.Throws<T>( TestDelegate code );T Assert.Throws<T>( TestDelegate code, string message );T Assert.Throws<T>( TestDelegate code, string message, params object[] parms);void Assert.DoesNotThrow( TestDelegate code );void Assert.DoesNotThrow( TestDelegate code, string message );void Assert.DoesNotThrow( TestDelegate code, string message, params object[] parms);Exception Assert.Catch( TestDelegate code );Exception Assert.Catch( TestDelegate code, string message );Exception Assert.Catch( TestDelegate code, string message, params object[] parms);Exception Assert.Catch( Type expectedExceptionType, TestDelegate code );Exception Assert.Catch( Type expectedExceptionType, TestDelegate code, string message );Exception Assert.Catch( Type expectedExceptionType, TestDelegate code, string message, params object[] parms);T Assert.Catch<T>( TestDelegate code );T Assert.Catch<T>( TestDelegate code, string message );T Assert.Catch<T>( TestDelegate code, string message, params object[] parms);In the above code TestDelegate is a delegate of the form void TestDelegate(), which is used toexecute the code in question. Under .NET 2.0, this may be an anonymous delegate. If compilingunder C# 3.0, it may be a lambda expression.The following example shows different ways of writing the same test.[TestFixture]public class AssertThrowsTests{ [Test] public void Tests() { // .NET 1.x Assert.Throws( typeof(ArgumentException), new TestDelegate(MethodThatThrows) ); // .NET 2.0 Assert.Throws<ArgumentException>( MethodThatThrows() ); Assert.Throws<ArgumentException>( delegate { throw new ArgumentException(); } ); // Using C# 3.0 Assert.Throws<ArgumentException>( () => throw new ArgumentException(); } ); }
  11. 11. void MethodThatThrows() { throw new ArgumentException(); }This example shows use of the return value to perform additional verification of the exception.[TestFixture]public class UsingReturnValue{ [Test] public void TestException() { MyException ex = Assert.Throws<MyException>( delegate { throw new MyException( "message", 42 ); } ); Assert.That( ex.Message, Is.EqualTo( "message" ) ); Assert.That( ex.MyParam, Is.EqualTo( 42 ) ); }This example does the same thing using the overload that includes a constraint.[TestFixture]public class UsingConstraint{ [Test] public void TestException() { Assert.Throws( Is.Typeof<MyException>() .And.Message.EqualTo( "message" ) .And.Property( "MyParam" ).EqualTo( 42 ), delegate { throw new MyException( "message", 42 ); } ); }Use the form that matches your style of coding.Exact Versus Derived TypesWhen used with a Type argument, Assert.Throws requires that exact type to be thrown. If youwant to test for any derived Type, use one of the forms that allows specifying a constraint.Alternatively, you may use Assert.Catch, which differs from Assert.Throws in allowingderived types. See the following code for examples:// Require an ApplicationException - derived types fail!Assert.Throws( typeof(ApplicationException), code );Assert.Throws<ApplicationException>()( code );// Allow both ApplicationException and any derived typeAssert.Throws( Is.InstanceOf( typeof(ApplicationException), code );Assert.Throws( Is.InstanceOf<ApplicationException>(), code );// Allow both ApplicationException and any derived typeAssert.Catch<ApplicationException>( code );
  12. 12. // Allow any kind of exceptionAssert.Catch( code ); Utility Methods 1. Four utility methods, Pass(), Fail(), Ignore() and Inconclusive() are provided in order to allow more direct control of the test process: 2. Assert.Pass(); 3. Assert.Pass( string message ); 4. Assert.Pass( string message, object[] parms ); 5. 6. Assert.Fail(); 7. Assert.Fail( string message ); 8. Assert.Fail( string message, object[] parms ); 9. 10. Assert.Ignore(); 11. Assert.Ignore( string message ); 12. Assert.Ignore( string message, object[] parms ); 13. 14. Assert.Inconclusive(); 15. Assert.Inconclusive( string message ); 16. Assert.Inconclusive( string message, object[] parms ); 17. The Assert.Pass method allows you to immediately end the test, recording it as successful. Since it causes an exception to be thrown, it is more efficient to simply allow the test to return. However, Assert.Pass allows you to record a message in the test result and may also make the test easier to read in some situations. Additionally, like the other methods on this page, it can be invoked from a nested method call with the result of immediately terminating test execution. 18. The Assert.Fail method provides you with the ability to generate a failure based on tests that are not encapsulated by the other methods. It is also useful in developing your own project-specific assertions. 19. Heres an example of its use to create a private assertion that tests whether a string contains an expected value. 20. public void AssertStringContains( string expected, string actual ) 21. { 22. AssertStringContains( expected, actual, string.Empty ); 23. } 24. 25. public void AssertStringContains( string expected, string actual, 26. string message ) 27. { 28. if ( actual.IndexOf( expected ) < 0 ) 29. Assert.Fail( message ); 30. } 31. The Assert.Ignore method provides you with the ability to dynamically cause a test or suite to be ignored at runtime. It may be called in a test, setup or fixture setup method. We recommend that you use this only in isolated cases. The category facility is provided for more extensive inclusion or exclusion of tests or you may elect to simply divide tests run on different occasions into different assemblies.
  13. 13. 32. The Assert.Inconclusive method indicates that the test could not be completed with the data available. It should be used in situations where another run with different data might run to completion, with either a success or failure outcome. StringAssert (NUnit 2.2.3) 33. The StringAssert class provides a number of methods that are useful when examining string values. 34. StringAssert.Contains( string expected, string actual ); 35. StringAssert.Contains( string expected, string actual, 36. string message ); 37. StringAssert.Contains( string expected, string actual, 38. string message, params object[] args ); 39. 40. StringAssert.StartsWith( string expected, string actual ); 41. StringAssert.StartsWith( string expected, string actual, 42. string message ); 43. StringAssert.StartsWith( string expected, string actual, 44. string message, params object[] args ); 45. 46. StringAssert.EndsWith( string expected, string actual ); 47. StringAssert.EndsWith( string expected, string actual, 48. string message ); 49. StringAssert.EndsWith( string expected, string actual, 50. string message, params object[] args ); 51. 52. StringAssert.AreEqualIgnoringCase( string expected, string actual ); 53. StringAssert.AreEqualIgnoringCase( string expected, string actual, 54. string message ); 55. StringAssert.AreEqualIgnoringCase( string expected, string actual, 56. string message params object[] args ); 57. 58. StringAssert.IsMatch( string regexPattern, string actual ); 59. StringAssert.IsMatch( string regexPattern, string actual, 60. string message ); 61. StringAssert.IsMatch( string regexPattern, string actual, 62. string message, params object[] args );CollectionAssert (NUnit 2.4 / 2.5) 63. The CollectionAssert class provides a number of methods that are useful when examining collections and their contents or for comparing two collections. 64. The AreEqual overloads succeed if the two collections contain the same objects, in the same order. AreEquivalent tests whether the collections contain the same objects, without regard to order. 65. Beginning with NUnit 2.4.6, these methods may be used on any object that implements IEnumerable. Prior to 2.4.6, only true collections were supported. 66. CollectionAssert.AllItemsAreInstancesOfType( IEnumerable collection, 67. Type expectedType ); 68. CollectionAssert.AllItemsAreInstancesOfType( IEnumerable collection, 69. Type expectedType, string message );
  14. 14. 70. CollectionAssert.AllItemsAreInstancesOfType( IEnumerable collection,71. Type expectedType, string message, params object[] args );72.73. CollectionAssert.AllItemsAreNotNull( IEnumerable collection );74. CollectionAssert.AllItemsAreNotNull( IEnumerable collection,75. string message );76. CollectionAssert.AllItemsAreNotNull( IEnumerable collection,77. string message, params object[] args );78.79. CollectionAssert.AllItemsAreUnique( IEnumerable collection );80. CollectionAssert.AllItemsAreUnique( IEnumerable collection,81. string message );82. CollectionAssert.AllItemsAreUnique( IEnumerable collection,83. string message, params object[] args );84.85. CollectionAssert.AreEqual( IEnumerable expected, IEnumerable actual );86. CollectionAssert.AreEqual( IEnumerable expected, IEnumerable actual,87. string message );88. CollectionAssert.AreEqual( IEnumerable expected, IEnumerable actual89. string message, params object[] args );90.91. CollectionAssert.AreEquivalent( IEnumerable expected, IEnumerable actual);92. CollectionAssert.AreEquivalent( IEnumerable expected, IEnumerable actual,93. string message );94. CollectionAssert.AreEquivalent( IEnumerable expected, IEnumerable actual95. string message, params object[] args );96.97. CollectionAssert.AreNotEqual( IEnumerable expected, IEnumerable actual );98. CollectionAssert.AreNotEqual( IEnumerable expected, IEnumerable actual,99. string message );100. CollectionAssert.AreNotEqual( IEnumerableon expected, IEnumerable actual101. string message, params object[] args );102.103. CollectionAssert.AreNotEquivalent( IEnumerable expected,104. IEnumerable actual );105. CollectionAssert.AreNotEquivalent( IEnumerable expected,106. IEnumerable actual, string message );107. CollectionAssert.AreNotEquivalent( IEnumerable expected,108. IEnumerable actual, string message, params object[] args );109.110. CollectionAssert.Contains( IEnumerable expected, object actual );111. CollectionAssert.Contains( IEnumerable expected, object actual,112. string message );113. CollectionAssert.Contains( IEnumerable expected, object actual114. string message, params object[] args );115.116. CollectionAssert.DoesNotContain( IEnumerable expected, object actual );117. CollectionAssert.DoesNotContain( IEnumerable expected, object actual,118. string message );119. CollectionAssert.DoesNotContain( IEnumerable expected, object actual
  15. 15. 120. string message, params object[] args ); 121. 122. CollectionAssert.IsSubsetOf( IEnumerable subset, IEnumerable superset ); 123. CollectionAssert.IsSubsetOf( IEnumerable subset, IEnumerable superset, 124. string message ); 125. CollectionAssert.IsSubsetOf( IEnumerable subset, IEnumerable superset, 126. string message, params object[] args ); 127. 128. CollectionAssert.IsNotSubsetOf( IEnumerable subset, IEnumerable superset); 129. CollectionAssert.IsNotSubsetOf( IEnumerable subset, IEnumerable superset, 130. string message ); 131. CollectionAssert.IsNotSubsetOf( IEnumerable subset, IEnumerable superset, 132. string message, params object[] args ); 133. 134. CollectionAssert.IsEmpty( IEnumerable collection ); 135. CollectionAssert.IsEmpty( IEnumerable collection, string message ); 136. CollectionAssert.IsEmpty( IEnumerable collection, string message, 137. params object[] args ); 138. 139. CollectionAssert.IsNotEmpty( IEnumerable collection ); 140. CollectionAssert.IsNotEmpty( IEnumerable collection, string message ); 141. CollectionAssert.IsNotEmpty( IEnumerable collection, string message, 142. params object[] args ); 143. The following methods are available beginning with NUnit 2.5 144. CollectionAssert.IsOrdered( IEnumerable collection ); 145. CollectionAssert.IsOrdered( IEnumerable collection, string message ); 146. CollectionAssert.IsOrdered( IEnumerable collection, string message, 147. params object[] args ); 148. 149. CollectionAssert.IsOrdered( IEnumerable collection, IComparer comparer ); 150. CollectionAssert.IsOrdered( IEnumerable collection, IComparer comparer, 151. string message ); 152. CollectionAssert.IsOrdered( IEnumerable collection, IComparer comparer, 153. string message, params object[] args );FileAssert (NUnit 2.4)The FileAssert class provides methods for comparing two files, which may be provided asStreams, as FileInfos or as strings giving the path to each file.FileAssert.AreEqual( Stream expected, Stream actual );FileAssert.AreEqual( Stream expected, Stream actual, string message );FileAssert.AreEqual( Stream expected, Stream actual, string message, params object[] args );
  16. 16. FileAssert.AreEqual( FileInfo expected, FileInfo actual );FileAssert.AreEqual( FileInfo expected, FileInfo actual, string message );FileAssert.AreEqual( FileInfo expected, FileInfo actual, string message, params object[] args );FileAssert.AreEqual( string expected, string actual );FileAssert.AreEqual( string expected, string actual, string message );FileAssert.AreEqual( string expected, string actual, string message, params object[] args );FileAssert.AreNotEqual( Stream expected, Stream actual );FileAssert.AreNotEqual( Stream expected, Stream actual, string message );FileAssert.AreNotEqual( Stream expected, Stream actual, string message, params object[] args );FileAssert.AreNotEqual( FileInfo expected, FileInfo actual );FileAssert.AreNotEqual( FileInfo expected, FileInfo actual, string message );FileAssert.AreNotEqual( FileInfo expected, FileInfo actual, string message, params object[] args );FileAssert.AreNotEqual( string expected, string actual );FileAssert.AreNotEqual( string expected, string actual, string message );FileAssert.AreNotEqual( string expected, string actual, string message, params object[] args );DirectoryAssert (NUnit 2.5)The DirectoryAssert class provides methods for making asserts about file system directories,which may be provided as DirectoryInfos or as strings giving the path to each directory.DirectoryAssert.AreEqual() and DirectoryAssert.AreNotEqual() compare two directories forequality. Directories are considered equal if they have the same FullName, Attributes,CreationTime and LastAccessTime.Note: Two different directories containing the same files are not considered to be equal.DirectoryAssert.AreEqual( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.AreEqual( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.AreEqual( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.AreEqual( string expected, string actual );DirectoryAssert.AreEqual( string expected, string actual, string message );DirectoryAssert.AreEqual( string expected, string actual,
  17. 17. string message, params object[] args );DirectoryAssert.AreNotEqual( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.AreNotEqual( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.AreNotEqual( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.AreNotEqual( string expected, string actual );DirectoryAssert.AreNotEqual( string expected, string actual, string message );DirectoryAssert.AreNotEqual( string expected, string actual, string message, params object[] args );DirectoryAssert.IsEmpty() and DirectoryAssert.IsNotEmpty() test whether the specifieddirectory is empty.DirectoryAssert.IsEmpty( DirectoryInfo directory );DirectoryAssert.IsEmpty( DirectoryInfo directory, string message );DirectoryAssert.IsEmpty( DirectoryInfo directory, string message, params object[] args );DirectoryAssert.IsEmpty( string directory );DirectoryAssert.IsEmpty( string directory, string message );DirectoryAssert.IsEmpty( string directory, string message, params object[] args );DirectoryAssert.IsNotEmpty( DirectoryInfo directory );DirectoryAssert.IsNotEmpty( DirectoryInfo directory, string message );DirectoryAssert.IsNotEmpty( DirectoryInfo directory, string message, params object[] args );DirectoryAssert.IsNotEmpty( string directory );DirectoryAssert.IsNotEmpty( string directory, string message );DirectoryAssert.IsNotEmpty( string directory, string message, params object[] args );DirectoryAssert.IsWithin() and DirectoryAssert.IsNotWithin() test whether the seconddirectory is a direct or indirect subdirectory of the first directory.DirectoryAssert.IsWithin( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.IsWithin( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.IsWithin( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.IsWithin( string expected, string actual );DirectoryAssert.IsWithin( string expected, string actual, string message );DirectoryAssert.IsWithin( string expected, string actual, string message, params object[] args );
  18. 18. DirectoryAssert.IsNotWithin( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.IsNotWithin( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.IsNotWithin( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.IsNotWithin( string expected, string actual );DirectoryAssert.IsNotWithin( string expected, string actual, string message );DirectoryAssert.IsNotWithin( string expected, string actual, string message, params object[] args );Constraint-Based Assert Model (NUnit 2.4)The constraint-based Assert model uses a single method of the Assert class for all assertions. Thelogic necessary to carry out each assertion is embedded in the constraint object passed as thesecond parameter to that method.Heres a very simple assert using the constraint model: Assert.That( myString, Is.EqualTo("Hello") );The second argument in this assertion uses one of NUnits syntax helpers to create anEqualConstraint. The same assertion could also be made in this form: Assert.That( myString, new EqualConstraint("Hello") );Using this model, all assertions are made using one of the forms of the Assert.That() method,which has a number of overloads...Assert.That( object actual, IResolveConstraint constraint )Assert.That( object actual, IResolveConstraint constraint, string message )Assert.That( object actual, IResolveConstraint constraint, string message, object[] parms )Assert.That( ActualValueDelegate del, IResolveConstraint constraint )Assert.That( ActualValueDelegate del, IResolveConstraint constraint, string message )Assert.That( ActualValueDelegate del, IResolveConstraint constraint, string message, object[] parms )Assert.That( ref T actual, IResolveConstraint constraint )Assert.That( ref T actual, IResolveConstraint constraint, string message )Assert.That( ref T actual, IResolveConstraint constraint, string message, object[] parms )Assert.That( bool condition );Assert.That( bool condition, string message );
  19. 19. Assert.That( bool condition, string message, object[] parms );Assert.That( TestDelegate del, IResolveConstraint constraint );If you derive your test fixture class from AssertionHelper, the Expect() method may be used inplace of Assert.That()...Expect( object actual, IResolveConstraint constraint )Expect( object actual, IResolveConstraint constraint, string message )Expect( object actual, IResolveConstraint constraint, string message, object[] parms )Expect( ActualValueDelegate del, IResolveConstraint constraint )Expect( ActualValueDelegate del, IResolveConstraint constraint, string message )Expect( ActualValueDelegate del, IResolveConstraint constraint, string message, object[] parms )Expect( ref T actual, IResolveConstraint constraint )Expect( ref T actual, IResolveConstraint constraint, string message )Expect( ref T actual, IResolveConstraint constraint, string message, object[] parms )Expect( bool condition );Expect( bool condition, string message );Expect( bool condition, string message, object[] parms );Expect( TestDelegate del, IResolveConstraint constraint );The overloads that take a bool work exactly like Assert.IsTrue.For overloads taking a constraint, the argument must be a object implementing the IConstraintinterface, which supports performing a test on an actual value and generating appropriatemessages. This interface is described in more detail under Custom Constraints.NUnit provides a number of constraint classes similar to the EqualConstraint used in theexample above. Generally, these classes may be used directly or through a syntax helper. Testfixture classes inheriting from AssertionHelper are able to use shorter forms. The valid formsare described on the pages related to each constraint. Note that the menu items listed to the rightgenerally reflect the names of the syntax helpers.Equal Constraint (NUnit 2.4 / 2.5)An EqualConstraint is used to test whether an actual value is equal to the expected valuesupplied in its constructor, optionally within a specified tolerance.ConstructorEqualConstraint(object expected )
  20. 20. SyntaxIs.EqualTo( object expected )Modifiers...IgnoreCase...AsCollection...NoClip...Within(object tolerance) .Ulps .Percent .Days .Hours .Minutes .Seconds .Milliseconds .Ticks...Using(IEqualityComparer comparer)...Using(IEqualityComparer<T> comparer)...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Comparing NumericsNumerics are compared based on their values. Different types may be compared successfully iftheir values are equal.Using the Within modifier, numerics may be tested for equality within a fixed or percenttolerance.Assert.That(2 + 2, Is.EqualTo(4.0));Assert.That(2 + 2 == 4);Assert.That(2 + 2, Is.Not.EqualTo(5));Assert.That(2 + 2 != 5);Assert.That( 5.0, Is.EqualTo( 5 );Assert.That( 5.5, Is.EqualTo( 5 ).Within(0.075);Assert.That( 5.5, Is.EqualTo( 5 ).Within(1.5).Percent;Comparing Floating Point ValuesValues of type float and double are normally compared using a tolerance specified by the Withinmodifier. The special values PositiveInfinity, NegativeInfinity and NaN compare as equal tothemselves.With version 2.5, floating-point values may be compared using a tolerance in "Units in the LastPlace" or ULPs. For certain types of numerical work, this is safer than a fixed tolerance becauseit automatically compensates for the added inaccuracy of larger numbers.Assert.That( 2.1 + 1.2, Is.EqualTo( 3.3 ).Within( .0005 );Assert.That( double.PositiveInfinity, Is.EqualTo( double.PositiveInfinity ));
  21. 21. Assert.That( double.NegativeInfinity, Is.EqualTo( double.NegativeInfinity ));Assert.That( double.NaN, Is.EqualTo( double.NaN ) );Assert.That( 20000000000000004.0,Is.EqualTo(20000000000000000.0).Within(1).Ulps);Comparing StringsString comparisons normally respect case. The IgnoreCase modifier causes the comparison tobe case-insensitive. It may also be used when comparing arrays or collections of strings.Assert.That( "Hello!", Is.Not.EqualTo( "HELLO!" ) );Assert.That( "Hello!", Is.EqualTo( "HELLO!" ).IgnoreCase );string[] expected = new string[] { "Hello", World" };string[] actual = new string[] { "HELLO", "world" };Assert.That( actual, Is.EqualTo( expected ).IgnoreCase;Comparing DateTimes and TimeSpansDateTimes and TimeSpans may be compared either with or without a tolerance. A tolerance isspecified using Within with either a TimeSpan as an argument or with a numeric valuefollowed by a one of the time conversion modifiers: Days, Hours, Minutes, Seconds,Milliseconds or Ticks.DateTime now = DateTime.Now;DateTime later = now + TimeSpan.FromHours(1.0);Assert.That( now, Is.EqualTo(now) );Assert.That( later. Is.EqualTo(now).Within(TimeSpan.FromHours(3.0);Assert.That( later, Is.EqualTo(now).Within(3).Hours;Comparing Arrays and CollectionsSince version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginningwith version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections maybe compared. With version 2.5, any IEnumerable is supported. Two arrays, collections orIEnumerables are considered equal if they have the the same dimensions and if each of thecorresponding elements is equal.If you want to treat two arrays of different shapes as simple collections for purposes ofcomparison, use the AsCollection modifier, which causes the comparison to be made element byelement, without regard for the rank or dimensions of the array. Note that jagged arrays (arraysof arrays) do not have a single underlying collection. The modifier would be applied to eacharray separately, which has no effect in most cases.int[] i3 = new int[] { 1, 2, 3 };double[] d3 = new double[] { 1.0, 2.0, 3.0 };int[] iunequal = new int[] { 1, 3, 2 };Assert.That(i3, Is.EqualTo(d3));Assert.That(i3, Is.Not.EqualTo(iunequal));
  22. 22. int array2x2 = new int[,] { { 1, 2 } { 3, 4 } };int array4 = new int[] { 1, 2, 3, 4 };Assert.That( array2x2, Is.Not.EqualTo( array4 ) );Assert.That( array2x2, Is.EqualTo( array4 ).AsCollection );Comparing DictionariesDictionaries implement ICollection, and NUnit has treated them as collections since version 2.4.However, this did not give useful results, since the dictionary entries had to be in the same orderfor the comparison to succeed and the underlying implementation had to be the same.Beginning with NUnit 2.5.6, NUnit has specific code for comparing dictionaries. Twodictionaries are considered equal if 1. The list of keys is the same - without regard to ordering. 2. The values associated with each key are equal.You can use this capability to compare any two objects implementing IDictionary. Generic andnon-generic dictionaries (Hashtables) may be successfully compared.User-Specified ComparersIf the default NUnit or .NET behavior for testing equality doesnt meet your needs, you cansupply a comparer of your own through the Using modifier. When used with EqualConstraint,you may supply an IEqualityComparer, IEqualityComparer<T>, IComparer,IComparer<T>; or Comparison<T> as the argument to Using.Assert.That( myObj1, Is.EqualTo( myObj2 ).Using( myComparer ) );Notes 1. When checking the equality of user-defined classes, NUnit makes use of the Equals override on the expected object. If you neglect to override Equals, you can expect failures non-identical objects. In particular, overriding operator== without overriding Equals has no effect. 2. The Within modifier was originally designed for use with floating point values only. Beginning with NUnit 2.4, comparisons of DateTime values may use a TimeSpan as a tolerance. Beginning with NUnit 2.4.2, non-float numeric comparisons may also specify a tolerance. 3. Beginning with NUnit 2.4.4, float and double comparisons for which no tolerance is specified use a default, use the value of GlobalSettings.DefaultFloatingPointTolerance. If this is not set, a tolerance of 0.0d is used. 4. Prior to NUnit 2.2.3, comparison of two NaN values would always fail, as specified by IEEE floating point standards. The new behavior, was introduced after some discussion becuase it seems more useful in tests. To avoid confusion, consider using Is.NaN where appropriate.
  23. 23. 5. When an equality test between two strings fails, the relevant portion of of both strings is displayed in the error message, clipping the strings to fit the length of the line as needed. Beginning with 2.4.4, this behavior may be modified by use of the NoClip modifier on the constraint. In addition, the maximum line length may be modified for all tests by setting the value of TextMessageWriter.MaximumLineLength in the appropriate level of setup. 6. When used with arrays, collections or dictionaries, EqualConstraint operates recursively. Any modifiers are saved and used as they apply to individual items. 7. A user-specified comparer will not be called by EqualConstraint if either or both arguments are null. If both are null, the Constraint succeeds. If only one is null, it fails. 8. NUnit has special semantics for comparing Streams and DirectoryInfos. For a Stream, the contents are compared. For a DirectoryInfo, the first-level directory contents are compared.Same As Constraint (NUnit 2.4)A SameAsConstraint is used to test whether the object passed as an actual value has the sameidentity as the object supplied in its constructor.ConstructorSameAsConstraint( object expected )SyntaxIs.SameAs( object expected )Examples of UseException ex1 = new Exception();Exception ex2 = ex1;Assert.That( ex2, Is.SameAs( ex1 ) );Exception ex3 = new Exception();Assert.That( ex3, Is.Not.SameAs( ex1 ) );Condition Constraints (NUnit 2.4)ConditionConstraints test a specific condition and are named for the condition they test. Theyverify that the actual value satisfies the condition. The following condition helpers are provided.NullConstraintActionTests that a value is Null.ConstructorNullConstraint()
  24. 24. SyntaxIs.NullExamples of UseAssert.That( anObject, Is.Null );Assert.That( anObject, Is.Not.Null );TrueConstraintActionTests that a value is true.ConstructorTrueConstraint()SyntaxIs.TrueExample of UseAssert.That( condition, Is.True );FalseConstraintActionTests that a value is false.ConstructorFalseConstraint()SyntaxIs.FalseExample of UseAssert.That( condition, Is.False );NaNConstraintActionTests that a value is floating-point NaN.ConstructorNaNConstraint()SyntaxIs.NaNExamples of UseAssert.That( aDouble, Is.NaN );
  25. 25. Assert.That( aDouble, Is.Not.NaN );EmptyConstraintActionTests that an object is an empty string, directory or collection.ConstructorEmptyConstraint()SyntaxIs.EmptyExamples of UseAssert.That( aString, Is.Empty );Assert.Thst( dirInfo, Is.Empty );Assert.That( collection, Is.Empty );Notes 1. EmptyConstraint creates and uses either an EmptyStringConstraint, EmptyDirectoryConstraint or EmptyCollectionConstraint depending on the argument tested. 2. A DirectoryInfo argument is required in order to test for an empty directory. To test whether a string represents a directory path, you must first construct a DirectoryInfo.UniqueItemsConstraintActionTests that an array, collection or other IEnumerable is composed of unique items with noduplicates.ConstructorUniqueItemsConstraint()SyntaxIs.UniqueExample of UseAssert.That( collection, Is.Unique );Comparison Constraints (NUnit 2.4 / 2.5)Comparison constraints are able to test whether one value is greater or less than another.Comparison constraints work on numeric values, as well as other objects that implement theIComparable interface or - beginning with NUnit 2.5 - IComparable<T>.
  26. 26. Beginning with NUnit 2.5, you may supply your own comparison algorithm through the Usingmodifier.GreaterThanConstraintActionTests that one value is greater than another.ConstructorGreaterThanConstraint(object expected)SyntaxIs.GreaterThan(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(7, Is.GreaterThan(3));Assert.That(myOwnObject, Is.GreaterThan(theExpected).Using(myComparer));GreaterThanOrEqualConstraintActionTests that one value is greater than or equal to another.ConstructorGreaterThanOrEqualConstraint(object expected)SyntaxIs.GreaterThanOrEqualTo(object expected)Is.AtLeast(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(7, Is.GreaterThanOrEqualTo(3));Assert.That(7, Is.AtLeast(3));Assert.That(7, Is.GreaterThanOrEqualTo(7));Assert.That(7, Is.AtLeast(7));Assert.That(myOwnObject, Is.GreaterThanOrEqualTo(theExpected).Using(myComparer));
  27. 27. LessThanConstraintActionTests that one value is less than another.ConstructorLessThanConstraint(object expected)SyntaxIs.LessThan(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(3, Is.LessThan(7));Assert.That(myOwnObject, Is.LessThan(theExpected).Using(myComparer));LessThanOrEqualConstraintActionTests that one value is less than or equal to another.ConstructorLessThanOrEqualConstraint(object expected)SyntaxIs.LessThanOrEqualTo(object expected)Is.AtMost(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(3, Is.LessThanOrEqualTo(7));Assert.That(3, Is.AtMost(7));Assert.That(3, Is.LessThanOrEqualTo(3));Assert.That(3, Is.AtMost(3));Assert.That(myOwnObject, Is.LessThanOrEqualTo(theExpected).Using(myComparer));
  28. 28. RangeConstraintActionConstructorRangeConstraint(IComparable from, IComparable to)SyntaxIs.InRange(IComparable from, IComparable to)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of Useint[] iarray = new int[] { 1, 2, 3 }Assert.That( 42, Is.InRange(1, 100) );Assert.That( iarray, Is.All.InRange(1, 3) );Assert.That(myOwnObject, Is.InRange(lowExpected, highExpected).Using(myComparer));Path Constraints (NUnit 2.5)Path constraints perform tests on paths, without reference to any actual files or directories. Thisallows testing paths that are created by an application for reference or later use, without anyeffect on the environment.Path constraints are intended to work across multiple file systems, and convert paths to acanonical form before comparing them.It is usually not necessary to know the file system of the paths in order to compare them. Wherenecessary, the programmer may use the IgnoreCase and RespectCase modifiers to providebehavior other than the system default.SamePathConstraintActionTests that two paths are equivalent.ConstructorSamePathConstraint( string expectedPath )SyntaxIs.SamePath( string expectedPath )Modifiers...IgnoreCase
  29. 29. ...RespectCaseExamples of UseAssert.That( "/folder1/./junk/../folder2", Is.SamePath( "/folder1/folder2" ) );Assert.That( "/folder1/./junk/../folder2/x", Is.Not.SamePath( "/folder1/folder2" ) );Assert.That( @"C:folder1folder2", Is.SamePath( @"C:Folder1Folder2" ).IgnoreCase );Assert.That( "/folder1/folder2", Is.Not.SamePath( "/Folder1/Folder2" ).RespectCase );SamePathOrUnderConstraintActionTests that one path is equivalent another path or that it is under it.ConstructorSamePathOrUnderConstraint( string expectedPath )SyntaxIs.SamePathOrUnder( string expectedPath )Modifiers...IgnoreCase...RespectCaseExamples of UseAssert.That( "/folder1/./junk/../folder2", Is.SamePathOrUnder( "/folder1/folder2" ) );Assert.That( "/folder1/junk/../folder2/./folder3", Is.SamePathOrUnder( "/folder1/folder2" ) );Assert.That( "/folder1/junk/folder2/folder3", Is.Not.SamePathOrUnder( "/folder1/folder2" ) );Assert.That( @"C:folder1folder2folder3", Is.SamePathOrUnder( @"C:Folder1Folder2" ).IgnoreCase );Assert.That( "/folder1/folder2/folder3", Is.Not.SamePathOrUnder( "/Folder1/Folder2" ).RespectCase );Type Constraints (NUnit 2.4)Type constraints perform tests that are specific to Types. The following type constraints areprovided: Syntax Helper Constructor OperationIs.TypeOf( Type ) ExactTypeConstraint( Type ) tests that an object is an exact Type
  30. 30. InstanceOfTypeConstraint( TypeIs.InstanceOfType( Type ) tests that an object is an instance of a Type )Is.AssignableFrom( Type AssignableFromConstraint( Type tests that one type is assignable from) ) anotherExamples of UseAssert.That("Hello", Is.TypeOf(typeof(string)));Assert.That("Hello", Is.Not.TypeOf(typeof(int)));Assert.That("Hello", Is.InstanceOfType(typeof(string)));Assert.That(5, Is.Not.InstanceOfType(typeof(string)));Assert.That( "Hello", Is.AssignableFrom(typeof(string)));Assert.That( 5, Is.Not.AssignableFrom(typeof(string)));// Using inheritanceExpect( 5, Not.InstanceOfType(typeof(string)));Expect( "Hello", AssignableFrom(typeOf(string)));String Constraints (NUnit 2.4)String constraints perform tests that are specific to strings. Attempting to test a non-string valuewith a string constraint is an error and gives an exception.The Text prefix is deprecated beginning with NUnit 2.5.1 and will be removed in NUnit 3.0.SubstringConstraintActionTests for a substring.ConstructorSubstringConstraint(string expected)SyntaxIs.StringContaining(string expected)Contains.Substring(string expected)ContainsSubstring(string expected)Contains(string expected)[Obsolete] Text.Contains(string expected)[Obsolete] Text.DoesNotContain(string expected)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"
  31. 31. Assert.That( phrase, Is.StringContaining( "tests fail" ) );Assert.That( phrase, Contains.Substring( "tests fail" ) );Assert.That( phrase, Is.Not.StringContaining( "tests pass" ) );Assert.That( phrase, Is.StringContaining( "make" ).IgnoreCase );Expect (phrase, Contains.Substring( "make" ).IgnoreCase );Notes 1. ContainsSubstring and Contains may appear only in the body of a constraint expression or when the inherited syntax is used. 2. Contains is not actually a string constraint but is converted to one when a string is being tested.StartsWithConstraintActionTests for an initial string.ConstructorStartsWithConstraint(string expected)SyntaxIs.StringStarting(string expected)StartsWith(string expected)[Obsolete] Text.StartsWith(string expected)[Obsolete] Text.DoesNotStartWith(string expected)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"Assert.That( phrase, Is.StringStarting( "Make" ) );Assert.That( phrase, Is.Not.StringStarting( "Break" ) );Assert.That( phrase, Has.Length.GreaterThan(10) .And.Not.StartsWith( "Break" ) );Expect( phrase, StartsWith( "Make" ) );Notes 1. StartsWith may appear only in the body of a constraint expression or when the inherited syntax is used.EndsWithConstraintActionTests for an ending string.
  32. 32. ConstructorEndsWithConstraint(string expected)SyntaxIs.StringEnding(string expected)EndsWith(string expected)[Obsolete] Text.EndsWith(string expected)[Obsolete] Text.DoesNotEndWith(string expected)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"Assert.That( phrase, Is.StringEnding( "!" ) );Assert.That( phrase, Is.StringEnding( "PASSING!" ).IgnoreCase );Expect( phrase, EndsWith( "!" ) );Notes 1. EndsWith may appear only in the body of a constraint expression or when the inherited syntax is used.RegexConstraintActionTests that a pattern is matched.ConstructorRegexConstraint(string pattern)SyntaxIs.StringMatching(string pattern)Matches(string pattern)[Obsolete] Text.Matches(string pattern)[Obsolete] Text.DoesNotMatch(string pattern)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"Assert.That( phrase, Is.StringMatching( "Make.*tests.*pass" ) );Assert.That( phrase, Is.Not.StringMatching( "your.*passing.*tests" ) );Assert.That( phrase, Has.Length.GreaterThan(10) .And.Not.Matches( "your.*passing.*tests" ) );Expect( phrase, Matches( "Make.*pass" ) );
  33. 33. Notes 1. Matches may appear only in the body of a constraint expression or when the inherited syntax is used.Collection Constraints (NUnit 2.4 / 2.5)Collection constraints perform tests that are specific to collections. The following collectionconstraints are provided. Before NUnit 2.4.6, these constraints only operated on true Collections.Beginning with 2.4.6, they can work with any object that implements IEnumerable.Beginning with NUnit 2.4.2, use of an improper argument type caused tests to fail. Later releasesgive an error rather than a failure, so that negated constraints will not appear to succeed.For example, both of the following statements give an error in later releases, but the secondwould have succeeded in earlier versions of NUnit.int[] iarray = new int[] { 1, 2, 3 };Assert.That( 5, Is.SubsetOf( iarray ) ); // Fails in early releasesAssert.That( 5, Is.Not.SubsetOf( iarray ) ); /AllItemsConstraintActionApplies a constraint to each item in a collection, succeeding only if all of them succeed.ConstructorAllItemsConstraint(Constraint itemConstraint)SyntaxIs.All...Has.All...Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Is.All.Not.Null );Assert.That( sarray, Is.All.InstanceOf() );Assert.That( iarray, Is.All.GreaterThan(0) );Assert.That( iarray, Has.All.GreaterThan(0) );SomeItemsConstraintActionApplies a constraint to each item in a collection, succeeding if at least one of them succeeds.
  34. 34. ConstructorSomeItemsConstraint(Constraint itemConstraint)SyntaxHas.Some...Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Has.Some.GreaterThan(2) );Assert.That( sarray, Has.Some.Length(1) );NoItemConstraintActionApplies a constraint to each item in a collection, succeeding only if all of them fail.ConstructorNoItemConstraint(Constraint itemConstraint)SyntaxHas.None...Has.No...Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Has.None.Null );Assert.That( iarray, Has.No.Null );Assert.That( sarray, Has.None.EqualTo("d") );Assert.That( iarray, Has.None.LessThan(0) );UniqueItemsConstraintActionTests that a collection contains only unique items.ConstructorUniqueItemsConstraint()SyntaxIs.UniqueExample of Usestring[] sarray = new string[] { "a", "b", "c" };Assert.That( sarray, Is.Unique );
  35. 35. Notes 1. ??CollectionContainsConstraintActionTests that a collection contains an object.ConstructorCollectionContainsConstraint( object )SyntaxHas.Member( object )Contains.Item( object )Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Has.Member(3) );Assert.That( sarray, Has.Member("b") );Assert.That( sarray, Contains.Item("c") );Assert.That( sarray, Has.No.Member("x") );Notes 1. For references, Has.Member uses object equality to find a member in a collection. To check for an object equal to an item the collection, use Has.Some.EqualTo(...).CollectionEquivalentConstraintActionTests that two collections are equivalent - that they contain the same items, in any order.ConstructorCollectionEquivalentConstraint( IEnumerable other )SyntaxIs.EquivalentTo( IEnumerable other )Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( new string[] { "c", "a", "b" }, Is.EquivalentTo( sarray ) );Assert.That( new int[] { 1, 2, 2 }, Is.Not.EquivalentTo( iarray ) );
  36. 36. Notes 1. To compare collections for equality, use Is.EqualTo().CollectionSubsetConstraintActionTests that one collection is a subset of another.ConstructorCollectionSubsetConstraint( ICollection )SyntaxIs.SubsetOf( IEnumerable )Example of Useint[] iarray = new int[] { 1, 2, 3 };Assert.That( new int[] { 1, 3 }, Is.SubsetOf( iarray ) );CollectionOrderedConstraint (NUnit 2.5)ActionTests that a collection is ordered.ConstructorCollectionOrderedConstraint()SyntaxIs.OrderedModifiers...Descending...By(string propertyName)...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "c", "b", "a" };string[] sarray2 = new string[] ( "a", "aa", "aaa" );Assert.That( iarray, Is.Ordered );Assert.That( sarray, Is.Ordered.Descending );Assert.That( sarray2, Is.Ordered.By("Length");
  37. 37. Notes 1. Modifiers may be combined and may appear in any order. If the same modifier is used more than once, the result is undefined. 2. The syntax of Is.Ordered has changed from earlier betas. 3. Property Constraint (NUnit 2.4.2) 4. PropertyConstraint is used to test for existence of a named property and optionally tests its value. It may also be used as a prefix for other constraints to be applied to the property. Syntax Helper Constructor OperationHas.Property( string ) PropertyConstraint( string ) tests that a specific property existsHas.Property( string, PropertyConstraint( string, tests that the value of a property is equalobject ) object ) to the value providedHas.Property( string, applies the following constraint to the PropertyConstraintConstraint)... value of a named property tests that the objects Length property isHas.Length( int ) PropertyConstraint equal to the value given tests that the objects Count property isHas.Count( int ) PropertyConstraint equal to the value givenThrows Constraint (NUnit 2.5)ThrowsConstraint is used to test that some code, represented as a delegate, throws a particularexception. It may be used alone, to merely test the type of constraint, or with an additionalconstraint to be applied to the exception specified as an argument. p>The relatedThrowsNothingConstraint simply asserts that the delegate does not throw an exception.ConstructorsThrowsConstraint(Type expectedType)ThrowsConstraint<T>()ThrowsConstraint(Type expectedType, Constraint constraint)ThrowsConstraint<T>(Constraint constraint)ThrowsNothingConstraint()SyntaxThrows.ExceptionThrows.TargetInvocationExceptionThrows.ArgumentExceptionThrows.InvalidOperationExceptionThrows.TypeOf(Type expectedType)Throws.TypeOf<T>()Throws.InstanceOf(Type expectedType)Throws.InstanceOf<T>()Throws.NothingThrows.InnerException
  38. 38. Examples of Use// .NET 1.1Assert.That( new TestDelegate(SomeMethod), Throws.TypeOf(typeof(ArgumentException)));Assert.That( new TestDelegate(SomeMethod), Throws.Exception.TypeOf(typeof(ArgumentException)));Assert.That( new TestDelegate(SomeMethod), Throws.TypeOf(typeof(ArgumentException)) .With.Property("Parameter").EqualTo("myParam"));Assert.That( new TestDelegate(SomeMethod), Throws.ArgumentException );Assert.That( new TestDelegate(SomeMethod), Throws.TargetInvocationException .With.InnerException.TypeOf(ArgumentException));// .NET 2.0Assert.That( SomeMethod, Throws.TypeOf<ArgumentException>());Assert.That( SomeMethod, Throws.Exception.TypeOf<ArgumentException>());Assert.That( SomeMethod, Throws.TypeOf<ArgumentException>() .With.Property("Parameter").EqualTo("myParam"));Assert.That( SomeMethod, Throws.ArgumentException );Assert.That( SomeMethod, Throws.TargetInvocationException .With.InnerException.TypeOf<ArgumentException>());Notes 1. Throws.Exception may be followed by further constraints, which are applied to the exception itself as shown in the last two examples above. It may also be used alone to verify that some exception has been thrown, without regard to type. This is not a recommended practice since you should normally know what exception you are expecting. 2. Throws.TypeOf and Throws.InstanceOf are provided as a shorter syntax for this common test. They work exactly like the corresponding forms following Throws.Exception. 3. Throws.TargetInvocationException/b>, Throws.ArgumentException and Throws.InvalidOperationException provide a shortened form for some common exceptions. 4. Used alone, Throws.InnerException simply tests the InnerException value of the thrown exception. More commonly, it will be used in combination with a test for the type of the outer exception as shown in the examples above.Compound Constraints (NUnit 2.4)Compound constraints are used to combine other constraints in various ways. Syntax Helper Constructor OperationIs.Not... NotConstraint( Constraint ) Negates or reverses the effect of a constraint
  39. 39. Tests that all members of a collection matchIs.All... AllItemsConstraint( Constraint ) the constraintConstraint & AndConstraint( Constraint, Tests that both of the constraints are metConstraint Constraint )Constraint | OrConstraint( Constraint, Tests that at least one of the constraints is metConstraint Constraint )Examples of UseAssert.That( 2 + 2, Is.Not.EqualTo( 5 );Assert.That( new int[] { 1, 2, 3 }, Is.All.GreaterThan( 0 ) );Assert.That( 2.3, Is.GreaterThan( 2.0 ) & Is.LessThan( 3.0 ) );Assert.That( 3, Is.LessThan( 5 ) | Is.GreaterThan( 10 ) );// Using inheritanceExpect( 2 + 2, Not.EqualTo( 5 ) );Expect( 2.3, GreaterThan( 2.0 ) & LessThan( 3.0 ) );Delayed Constraint (NUnit 2.5)DelayedConstraint delays the application of another constraint until a certain amount of timehas passed. In its simplest form, it replaces use of a Sleep in the code but it also supports polling,which may allow use of a longer maximum time while still keeping the tests as fast as possible.The After modifier is permitted on any constraint, and the delay applies to the entire expressionup to the point where After appears.Use of a DelayedConstraint with a value argument makes no sense, since the value will beextracted at the point of call. Its intended use is with delegates and references. If a delegate isused with polling, it may be called multiple times so only methods without side effects should beused in this way. Syntax Constructor Operation HelperAfter(int) DelayedConstraint(Constraint, int) tests that a constraint is satisfied after a delay. DelayedConstraint(Constraint, int, tests that a constraint is satisfied after a delayAfter(int, int) int) using polling.List Mapper (NUnit 2.4.2)Unlike Constraint classes, ListMapper is used to modify the actual value argument toAssert.That(). It transforms the actual value, which must be a collection, creating a newcollection to be tested against the supplied constraint. Currently, ListMapper supports onetransformation: creating a collection of property values.
  40. 40. Normally, ListMapper will be used through the List.Map() syntax helper or the inherited syntaxequivalent, Map(). The following example shows three forms of the same assert:string[] strings = new string[] { "a", "ab", "abc" };int[] lengths = new int[] { 1, 2, 3 };Assert.That(List.Map(strings).Property("Length"), Is.EqualTo(lengths));Assert.That(new ListMapper(strings).Property("Length"), Is.EqualTo(lengths));// Assuming inheritance from AssertionHelperExpect(Map(strings).Property("Length"), EqualTo(lengths));ReusableConstraint (NUnit 2.5.6)Normally constraints just work. However, attempting to reuse the same constraint in severalplaces can lead to unexpected results.Consider the following code as an example: Constraint myConstraint = Is.Not.Null; Assert.That("not a null", myConstraint); // Passes, of course Assert.That("not a null", myConstraint); // Fails! Whats that about?Well save the technical explanation for later and show the solution first: ReusableConstraint myConstraint = Is.Not.Null; Assert.That("not a null", myConstraint); // Passes Assert.That("not a null", myConstraint); // PassesOr alternatively.. var myConstraint = new ReusableConstraint(Is.Not.Null); Assert.That("not a null", myConstraint); // Passes Assert.That("not a null", myConstraint); // PassesTechnical ExplanationIn the original example, the value assigned to myConstraint is known as an unresolvedconstraint. In fact, its an unresolved NullConstraint, because that was the last constraintencountered in the expression. Its associated with a Not operator that has not yet been applied.Thats OK for use with Assert.That(), because the method knows how to resolve a constraintbefore using it. Assert.That() resolves this constraint to a NotConstraint referencing the originalNullConstraint.Of course, the original reference in myConstraint is left unchanged in all of this. But theEqualConstraint it points to has now been resolved. It is now a resolved constraint and cant be
  41. 41. resolved again by the second Assert.That(), which only sees the NullConstraint and not theNotConstraint.So, for reusability, what we want to save is the result of resolving the constraint, in this case NotConstraint => NullConstraintThats what ReusableConstraint does for us. It resolves the full expression and saves the result. Then itpasses all operations on to that saved result.When to Use ItUse this constraint any time you want to reuse a constraint expression and youll be safe.If you like to take chances, youll find that you can avoid using it in the following cases... 1. With a simple constraint involving no operators, like... 2. Constraint myConstraint = Is.Null; 3. Constraint myConstraint = Is.EqualTo(42); 4. With any constraint you construct using new, without using the "dotted" constraint syntax... 5. Constraint myConstraint = new NotConstraint(new NullConstraint()); 6. Constraint myConstraint = new AndConstraint( 7. new GreaterThanConstraint(0), 8. new LessThanConstraint(100)); However, there is no significant penalty to using ReusableConstraint. It makes your intent much clearer and the exceptions listed are accidents of the internal implementation and could disappear in future releases.AttributesVersion 1 of NUnit used the classic approach to identifying tests based on inheritance andnaming conventions. From version 2.0 on, NUnit has used custom attributes for this purpose.Because NUnit test fixtures do not inherit from a framework class, the developer is free to useinheritance in other ways. And because there is no arbitrary convention for naming tests, thechoice of names can be entirely oriented toward communicating the purpose of the test.All NUnit attributes are contained in the NUnit.Framework namespace. Each source file thatcontains tests must include a using statement for that namespace and the project must referencethe framework assembly, nunit.framework.dll.Beginning with NUnit 2.4.6, NUnits attributes are no longer sealed and any attributes that derivefrom them will be recognized by NUnit.
  42. 42. CategoryAttribute (NUnit 2.2)The Category attribute provides an alternative to suites for dealing with groups of tests. Eitherindividual test cases or fixtures may be identified as belonging to a particular category. Both thegui and console test runners allow specifying a list of categories to be included in or excludedfrom the run. When categories are used, only the tests in the selected categories will be run.Those tests in categories that are not selected are not reported at all.This feature is accessible by use of the /include and /exclude arguments to the console runner andthrough a separate "Categories" tab in the gui. The gui provides a visual indication of whichcategories are selected at any time.Test Fixture Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [Category("LongRunning")] public class LongRunningTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Category("LongRunning")> Public Class LongRunningTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] [Category("LongRunning")] public __gc class LongRunningTests { // ... };}#include "cppsample.h"
  43. 43. namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Category("LongRunning") */public class LongRunningTests{ // ...}Test Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Category("Long")] public void VeryLongTest() { /* ... */ }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Category("Long")> Public Sub VeryLongTest() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [Test][Category("Long")] void VeryLongTest(); };}
  44. 44. #include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Category("Long") */ public void VeryLongTest() { /* ... */ }}Custom Category AttributesBeginning with NUnit 2.4, it is possible to define custom attributes that derive fromCategoryAttribute and have them recognized by NUnit. The default protected constructor ofCategoryAttribute sets the category name to the name of your class.Heres an example that creates a category of Critical tests. It works just like any other category,but has a simpler syntax. A test reporting system might make use of the attribute to providespecial reports.[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]public class CriticalAttribute : CategoryAttribute { }...[Test, Critical]public void MyTest(){ /*...*/ }CombinatorialAttribute (NUnit 2.5)The CombinatorialAttribute is used on a test to specify that NUnit should generate test casesfor all possible combinations of the individual data items provided for the parameters of a test.Since this is the default, use of this attribute is optional.ExampleThe following test will be executed six times, as follows: MyTest(1, "A") MyTest(1, "B")
  45. 45. MyTest(2, "A") MyTest(2, "B") MyTest(3, "A") MyTest(3, "B")[Test, Combinatorial]public void MyTest( [Values(1,2,3)] int x, [Values("A","B")] string s){ ...}CultureAttribute (NUnit 2.4.2)The Culture attribute is used to specify cultures for which a test or fixture should be run. It doesnot affect the culture setting, but merely uses it to determine whether to run the test. If you wishto change the culture when running a test, use the SetCulture attribute instead.If the specified culture requirements for a test are not met it is skipped. In the gui, the tree nodefor the test remains gray and the status bar color is not affected.One use of the Culture attribute is to provide alternative tests under different cultures. You mayspecify either specific cultures, like "en-GB" or neutral cultures like "de".Test Fixture Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [Culture("fr-FR")] public class FrenchCultureTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Culture("fr-FR")> Public Class FrenchCultureTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;
  46. 46. namespace NUnitTests{ [TestFixture] [Culture("fr-FR")] public __gc class FrenchCultureTests { // ... };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Culture("fr-FR") */public class FrenchCultureTests{ // ...}Test Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Culture(Exclude="en,de")] public void SomeTest() { /* ... */ }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Culture(Exclude="en,de")> Public Sub SomeTest() ... End Sub End ClassEnd Namespace
  47. 47. #using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [Test][Culture(Exclude="en,de")] void SomeTest(); };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Culture(Exclude=en,de") */ public void SomeTest() { /* ... */ }}DatapointAttribute / DatapointsAttribute (NUnit 2.5) (Experimental)The Datapoint and Datapoints attributes are used to provide data for Theories and are ignoredfor ordinary tests - including tests with parameters.DataPointAttributeWhen a Theory is loaded, NUnit creates arguments for each of its parameters by using any fieldsof the same type as the parameter annotated with the DatapointAttribute. Fields must bemembers of the class containing the Theory and their Type must exactly match the argument forwhich data is being supplied.DataPointsAttributeIn addition to specifying individual datapoints, collections of datapoints may be provided by useof the DatapointsAttribute - note the spelling. This attribute may be placed on methods orproperties in addition to fields. The returned value must be either an array of the required type or(beginning with NUnit 2.5.5) an IEnumerable<T> returning an enumeration of the requiredtype. The data Type must exactly match the argument for which data is being supplied.
  48. 48. Automatically Supplied DatapointsIt is normally not necessary to specify datapoints for boolean or enum arguments. Beginningwith version 2.5.4, NUnit automatically supplies values of true and false for boolean argumentsand will supply all defined values of any enumeration.If for some reason you dont wish to use all possible values, you can override this behavior bysupplying your own datapoints. If you supply any datapoints for an argument, automaticdatapoint generation is suppressed.Description (NUnit 2.4)The Description attribute is used to apply descriptive text to a Test, TestFixture or Assembly.The text appears in the XML output file and is shown in the Test Properties dialog.Example:[assembly: Description("Assembly description here")]namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture, Description("Fixture description here")] public class SomeTests { [Test, Description("Test description here")] public void OneTest() { /* ... */ } }}<assembly: Description("Assembly description here")>Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Description("Fixture description here")>_ Public Class SomeTests <Test(), Description("Test description here")>_ Public Sub OneTest() ... End Sub End ClassEnd Namespace[assembly:Description("Assembly description here")]#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;
  49. 49. namespace NUnitTests{ [TestFixture, Description("Fixture description here")] public __gc class SomeTests { [Test, Description("Test description here")] void OneTest(); };}#include "cppsample.h"namespace NUnitTests { // ...}/** @assembly NUnit.Framework.Description("Assembly description here") */package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Description("Fixture description here") */public class SomeTests{ /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Description("Test description here") */ public void OneTest() { /* ... */ }}Note: The Test and TestFixture attributes continue to support an optional Description property.The Description attribute should be used for new applciations. If both are used, the Descriptionattribute takes precedence.ExpectedExceptionAttribute (NUnit 2.0 plus Updates)This is the way to specify that the execution of a test will throw an exception. This attribute has anumber of positional and named parameters, which we will discuss in separate sectionsaccording to the purpose they serve.Specifying the Expected Exception TypeThe original attribute, introduced with NUnit 2.0 took a single argument giving the exact type ofthe expected exception. For example...[ExpectedException( typeof( ArgumentException ) )]public void TestMethod(){...
  50. 50. Beginning with NUnit 2.2.4, it became possible to specify the type of exception as a string,avoiding the need for a reference to the defining assembly...[ExpectedException( "System.ArgumentException" ) )]public void TestMethod(){...The above two examples function identically: the test only succeeds if a System.Argumentexception is thrown.Specifying the Expected MessageNUnit 2.1 introduced a constructor with a second argument, specifying the exact text of themessage property of the exception. After NUnit 2.2.4, the same extension was made to theconstructor taking a string argument. With NUnit 2.4, these arguments are marked obsolete, anda named parameter is provided instead...// Obsolete form:[ExpectedException( typeof( ArgumentException ), "expected message" )][ExpectedException( "System.ArgumentException", "expected message" )]// Prefered form:[ExpectedException( typeof( ArgumentException ), ExpectedMessage="expectedmessage" )][ExpectedException( "System.ArgumentException", ExpectedMessage="expectedmessage" )]With NUnit 2.4, it is possible to specify additional tests on the exception message, beyond asimple exact match. This is done using the MatchType named parameter, whose argument is anenumeration, defined as follows:public enum MessageMatch{ /// Expect an exact match Exact, /// Expect a message containing the parameter string Contains, /// Match the regular expression provided as a parameter Regex, /// Expect a message starting with the parameter string StartsWith}The following example is for a test that passes only if an ArgumentException with a messagecontaining "unspecified" is received.[ExpectedException( typeof( ArgumentException),ExpectedMessage="unspecified", MatchType=MessageMatch.Contains )]public void TestMethod(){
  51. 51. ...If MatchType is not specified, an exact match is used as before.Specifying a Custom Error MessageWith NUnit 2.4, it is possible to specify a custom message to be displayed if theExpectedException attribute is not satisfied. This is done through the UserMessage namedparameter...[ExpectedException( typeof( ArgumentException ), UserMessage="Custom message")]public void TestMethod(){...Handling the Exception in CodeIf the processing required for an exception is too complex to express in the attribute declaration,the normal practice is to process it in the test code using a try/catch block. As an alternative,NUnit 2.4 allows designating a method that will be called to process the exception. This isparticularly useful when multiple exceptions need to be processed in the same way.An common exception handler may be designated by implementing theIExpectExceptionInterface, which is defined as follows...public interface IExpectException{ void HandleException( System.Exception ex );}The exception handler is only called for methods marked with the ExpectedException attribute.If all checks - including the type of the exception - are to be performed in code, the attribute maybe specified without any arguments in order to indicate that an exception is expected.An handler may be designated for a particular method using the Handler named parameter.[ExpectedException( Handler="HandlerMethod" )]public void TestMethod(){...}public void HandlerMethod( System.Exception ex ){...}
  52. 52. This technique may be used without implementing IExpectException or in combination with it.In the latter case, the designated handler applies to any method that specifies it, while the normalexception handler applies to any other methods that specify an ExpectedException.However it is specified, the handler method should examine the exception and Assert onwhatever properties are relevant. Any resulting failure message will then be consistent in formatwith other assertions performed in the tests.Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [ExpectedException(typeof(InvalidOperationException))] public void ExpectAnExceptionByType() { /* ... */ } [Test] [ExpectedException("System.InvalidOperationException")] public void ExpectAnExceptionByName() { /* ... */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), ExpectedException(GetType(Exception))> Public Sub ExpectAnExceptionByType() ... End Sub <TestFixture()> Public Class SuccessTests <Test(), ExpectedException("System.Exception")> Public Sub ExpectAnExceptionByName() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{

×