SlideShare une entreprise Scribd logo
1  sur  172
What Is NUnit? NUnit is a unit-testing framework for all .Net languages. Initially ported from
JUnit, the current production release, version 2.5, is the sixth major release of this xUnit based
unit testing tool for Microsoft .NET. It is written entirely in C# and has been completely
redesigned to take advantage of many .NET language features, for example custom attributes and
other 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 .NET
language 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 you
write 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 NUnit
tools 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 Assert
class.
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
• TestFixtureTearDown

Add References in Project Browse references from C:Program FilesNUnit
2.5.2binnet-2.0framework i.e. nunit.framework.dll


Assertions
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 contains
multiple assertions, any that follow the one that failed will not be executed. For this reason, it's
usually best to try for one assertion per test.

Each method may be called without a message, with a simple text message or with a message
and arguments. In the last case the message is formatted using the provided text and arguments.

Two Models

Before 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 people
prefer it.

Beginning with NUnit 2.4, a new "Constraint-based" model was introduced. This approach uses
a single method of the Assert class for all assertions, passing a Constraint object that specifies
the test to be performed.

This constraint-based model is now used internally by NUnit for all assertions. The methods of
the classic approach have been re-implemented on top of this new model.

Equality Asserts
These methods test whether the two arguments are equal. Overloaded methods are provided for
common value types so that languages that don't automatically box values can use them directly.

Comparing Numerics of Different Types

The method overloads that compare two objects make special provision so that numeric values of
different types compare as expected. This assert succeeds:

          Assert.AreEqual( 5, 5.0 );

Comparing Floating Point Values

Values of type float and double are normally compared using an additional argument that
indicates 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 not
provided. In earlier versions, or if the default has not been set, values are tested for exact
equality.

Special values are handled so that the following Asserts succeed:

          Assert.AreEqual ( double.PositiveInfinity, double.PositiveInfinity );
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 would
fail. We have made this change because the new behavior seems to be more useful in tests. To avoid
confusion, we suggest using the new Assert.IsNaN method where appropriate.

Comparing Arrays and Collections

Since version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginning
with version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections may
be compared. Two arrays or collections will be treated as equal by Assert.AreEqual if they have
the same dimensions and if each of the corresponding elements is equal.

Identity Asserts
Assert.AreSame and Assert.AreNotSame test whether the same objects are referenced by the
two 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 Asserts
Methods that test a specific condition are named for the condition they test and take the value
tested as their first argument and, optionally a message as the second. The following methods are
provided:

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 );
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 are
compatible with earlier versions of the NUnit framework, while those without "Is" are provided
for compatibility with NUnitLite.

Assert.IsEmpty and Assert.IsNotEmpty may be used to test either a string or a collection.
Comparisons (NUnit 2.2.4)
The following methods test whether one object is greater than than another. Contrary to the
normal order of Asserts, these methods are designed to be read in the "natural" English-language
or 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 to
the normal order of Asserts, these methods are designed to be read in the "natural" English-
language or mathematical order. Thus Assert.GreaterOrEqual( x, y ) asserts that x is greater
than 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 normal
order of Asserts, these methods are designed to be read in the "natural" English-language or
mathematical 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,
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 the
normal order of Asserts, these methods are designed to be read in the "natural" English-language
or 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,
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 );
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, it
attempts to invoke a code snippet, represented as a delegate, in order to verify that it throws a
particular exception.

It's also in a class by itself in that it returns an Exception, rather than void, if the Assert is
successful. 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 exception
thrown, 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 the
one 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,
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 to
execute the code in question. Under .NET 2.0, this may be an anonymous delegate. If compiling
under 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(); } );
  }
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 Types

When used with a Type argument, Assert.Throws requires that exact type to be thrown. If you
want 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 allowing
derived 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 type
Assert.Throws( Is.InstanceOf( typeof(ApplicationException), code );
Assert.Throws( Is.InstanceOf<ApplicationException>(), code );

// Allow both ApplicationException and any derived type
Assert.Catch<ApplicationException>( code );
// Allow any kind of exception
Assert.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. Here's 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.
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 );
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 actual
89.             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
    actual
95.             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
    actual
101.            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 actual
114.            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
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 as
Streams, 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 );
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 for
equality. 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,
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 specified
directory 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 second
directory 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 );
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. The
logic necessary to carry out each assertion is embedded in the constraint object passed as the
second parameter to that method.

Here's a very simple assert using the constraint model:

       Assert.That( myString, Is.EqualTo("Hello") );

The second argument in this assertion uses one of NUnit's syntax helpers to create an
EqualConstraint. 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 );
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 in
place 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 IConstraint
interface, which supports performing a test on an actual value and generating appropriate
messages. This interface is described in more detail under Custom Constraints.

NUnit provides a number of constraint classes similar to the EqualConstraint used in the
example above. Generally, these classes may be used directly or through a syntax helper. Test
fixture classes inheriting from AssertionHelper are able to use shorter forms. The valid forms
are described on the pages related to each constraint. Note that the menu items listed to the right
generally 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 value
supplied in its constructor, optionally within a specified tolerance.

Constructor
EqualConstraint(object expected )
Syntax
Is.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 Numerics

Numerics are compared based on their values. Different types may be compared successfully if
their values are equal.

Using the Within modifier, numerics may be tested for equality within a fixed or percent
tolerance.

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 Values

Values of type float and double are normally compared using a tolerance specified by the Within
modifier. The special values PositiveInfinity, NegativeInfinity and NaN compare as equal to
themselves.

With version 2.5, floating-point values may be compared using a tolerance in "Units in the Last
Place" or ULPs. For certain types of numerical work, this is safer than a fixed tolerance because
it 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 )
);
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 Strings

String comparisons normally respect case. The IgnoreCase modifier causes the comparison to
be 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 TimeSpans

DateTimes and TimeSpans may be compared either with or without a tolerance. A tolerance is
specified using Within with either a TimeSpan as an argument or with a numeric value
followed 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 Collections

Since version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginning
with version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections may
be compared. With version 2.5, any IEnumerable is supported. Two arrays, collections or
IEnumerables are considered equal if they have the the same dimensions and if each of the
corresponding elements is equal.

If you want to treat two arrays of different shapes as simple collections for purposes of
comparison, use the AsCollection modifier, which causes the comparison to be made element by
element, without regard for the rank or dimensions of the array. Note that jagged arrays (arrays
of arrays) do not have a single underlying collection. The modifier would be applied to each
array 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));
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 Dictionaries

Dictionaries 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 order
for 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. Two
dictionaries 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 and
non-generic dictionaries (Hashtables) may be successfully compared.

User-Specified Comparers

If the default NUnit or .NET behavior for testing equality doesn't meet your needs, you can
supply 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.
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 same
identity as the object supplied in its constructor.

Constructor
SameAsConstraint( object expected )

Syntax
Is.SameAs( object expected )

Examples of Use
Exception 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. They
verify that the actual value satisfies the condition. The following condition helpers are provided.

NullConstraint

Action

Tests that a value is Null.

Constructor
NullConstraint()
Syntax
Is.Null

Examples of Use
Assert.That( anObject, Is.Null );
Assert.That( anObject, Is.Not.Null );

TrueConstraint

Action

Tests that a value is true.

Constructor
TrueConstraint()

Syntax
Is.True

Example of Use
Assert.That( condition, Is.True );

FalseConstraint

Action

Tests that a value is false.

Constructor
FalseConstraint()

Syntax
Is.False

Example of Use
Assert.That( condition, Is.False );

NaNConstraint

Action

Tests that a value is floating-point NaN.

Constructor
NaNConstraint()

Syntax
Is.NaN

Examples of Use
Assert.That( aDouble, Is.NaN );
Assert.That( aDouble, Is.Not.NaN );

EmptyConstraint

Action

Tests that an object is an empty string, directory or collection.

Constructor
EmptyConstraint()

Syntax
Is.Empty

Examples of Use
Assert.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.

UniqueItemsConstraint

Action

Tests that an array, collection or other IEnumerable is composed of unique items with no
duplicates.

Constructor
UniqueItemsConstraint()

Syntax
Is.Unique

Example of Use
Assert.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 the
IComparable interface or - beginning with NUnit 2.5 - IComparable<T>.
Beginning with NUnit 2.5, you may supply your own comparison algorithm through the Using
modifier.

GreaterThanConstraint

Action

Tests that one value is greater than another.

Constructor
GreaterThanConstraint(object expected)

Syntax
Is.GreaterThan(object expected)

Modifiers
...Using(IComparer comparer)
...Using(IComparer<T> comparer)
...Using(Comparison<T> comparer)

Examples of Use
Assert.That(7, Is.GreaterThan(3));
Assert.That(myOwnObject,
    Is.GreaterThan(theExpected).Using(myComparer));

GreaterThanOrEqualConstraint

Action

Tests that one value is greater than or equal to another.

Constructor
GreaterThanOrEqualConstraint(object expected)

Syntax
Is.GreaterThanOrEqualTo(object expected)
Is.AtLeast(object expected)

Modifiers
...Using(IComparer comparer)
...Using(IComparer<T> comparer)
...Using(Comparison<T> comparer)

Examples of Use
Assert.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));
LessThanConstraint

Action

Tests that one value is less than another.

Constructor
LessThanConstraint(object expected)

Syntax
Is.LessThan(object expected)

Modifiers
...Using(IComparer comparer)
...Using(IComparer<T> comparer)
...Using(Comparison<T> comparer)

Examples of Use
Assert.That(3, Is.LessThan(7));
Assert.That(myOwnObject,
    Is.LessThan(theExpected).Using(myComparer));

LessThanOrEqualConstraint

Action

Tests that one value is less than or equal to another.

Constructor
LessThanOrEqualConstraint(object expected)

Syntax
Is.LessThanOrEqualTo(object expected)
Is.AtMost(object expected)

Modifiers
...Using(IComparer comparer)
...Using(IComparer<T> comparer)
...Using(Comparison<T> comparer)

Examples of Use
Assert.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));
RangeConstraint

Action

Constructor
RangeConstraint(IComparable from, IComparable to)

Syntax
Is.InRange(IComparable from, IComparable to)

Modifiers
...Using(IComparer comparer)
...Using(IComparer<T> comparer)
...Using(Comparison<T> comparer)

Examples of Use
int[] 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. This
allows testing paths that are created by an application for reference or later use, without any
effect on the environment.

Path constraints are intended to work across multiple file systems, and convert paths to a
canonical form before comparing them.

It is usually not necessary to know the file system of the paths in order to compare them. Where
necessary, the programmer may use the IgnoreCase and RespectCase modifiers to provide
behavior other than the system default.

SamePathConstraint

Action

Tests that two paths are equivalent.

Constructor
SamePathConstraint( string expectedPath )

Syntax
Is.SamePath( string expectedPath )

Modifiers
...IgnoreCase
...RespectCase

Examples of Use
Assert.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 );

SamePathOrUnderConstraint

Action

Tests that one path is equivalent another path or that it is under it.

Constructor
SamePathOrUnderConstraint( string expectedPath )

Syntax
Is.SamePathOrUnder( string expectedPath )

Modifiers
...IgnoreCase
...RespectCase

Examples of Use
Assert.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 are
provided:

     Syntax Helper                  Constructor                             Operation

Is.TypeOf( Type )        ExactTypeConstraint( Type )       tests that an object is an exact Type
InstanceOfTypeConstraint( Type
Is.InstanceOfType( Type )                                  tests that an object is an instance of a Type
                            )

Is.AssignableFrom( Type AssignableFromConstraint( Type tests that one type is assignable from
)                       )                              another


Examples of Use
Assert.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 inheritance
Expect( 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 value
with 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.

SubstringConstraint

Action

Tests for a substring.

Constructor
SubstringConstraint(string expected)

Syntax
Is.StringContaining(string expected)
Contains.Substring(string expected)
ContainsSubstring(string expected)
Contains(string expected)
[Obsolete] Text.Contains(string expected)
[Obsolete] Text.DoesNotContain(string expected)

Modifiers
...IgnoreCase

Examples of Use
string phrase = "Make your tests fail before passing!"
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.

StartsWithConstraint

Action

Tests for an initial string.

Constructor
StartsWithConstraint(string expected)

Syntax
Is.StringStarting(string expected)
StartsWith(string expected)
[Obsolete] Text.StartsWith(string expected)
[Obsolete] Text.DoesNotStartWith(string expected)

Modifiers
...IgnoreCase

Examples of Use
string 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.

EndsWithConstraint

Action

Tests for an ending string.
Constructor
EndsWithConstraint(string expected)

Syntax
Is.StringEnding(string expected)
EndsWith(string expected)
[Obsolete] Text.EndsWith(string expected)
[Obsolete] Text.DoesNotEndWith(string expected)

Modifiers
...IgnoreCase

Examples of Use
string 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.

RegexConstraint

Action

Tests that a pattern is matched.

Constructor
RegexConstraint(string pattern)

Syntax
Is.StringMatching(string pattern)
Matches(string pattern)
[Obsolete] Text.Matches(string pattern)
[Obsolete] Text.DoesNotMatch(string pattern)

Modifiers
...IgnoreCase

Examples of Use
string 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" ) );
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 collection
constraints 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 releases
give 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 second
would have succeeded in earlier versions of NUnit.

int[] iarray = new int[] { 1, 2, 3 };

Assert.That( 5, Is.SubsetOf( iarray ) ); // Fails in early releases
Assert.That( 5, Is.Not.SubsetOf( iarray ) ); /

AllItemsConstraint

Action

Applies a constraint to each item in a collection, succeeding only if all of them succeed.

Constructor
AllItemsConstraint(Constraint itemConstraint)

Syntax
Is.All...
Has.All...

Examples of Use
int[] 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) );

SomeItemsConstraint

Action

Applies a constraint to each item in a collection, succeeding if at least one of them succeeds.
Constructor
SomeItemsConstraint(Constraint itemConstraint)

Syntax
Has.Some...

Examples of Use
int[] 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) );

NoItemConstraint

Action

Applies a constraint to each item in a collection, succeeding only if all of them fail.

Constructor
NoItemConstraint(Constraint itemConstraint)

Syntax
Has.None...
Has.No...

Examples of Use
int[] 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) );

UniqueItemsConstraint

Action

Tests that a collection contains only unique items.

Constructor
UniqueItemsConstraint()

Syntax
Is.Unique

Example of Use
string[] sarray = new string[] { "a", "b", "c" };

Assert.That( sarray, Is.Unique );
Notes

   1. ??

CollectionContainsConstraint

Action

Tests that a collection contains an object.

Constructor
CollectionContainsConstraint( object )

Syntax
Has.Member( object )
Contains.Item( object )

Examples of Use
int[] 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(...).

CollectionEquivalentConstraint

Action

Tests that two collections are equivalent - that they contain the same items, in any order.

Constructor
CollectionEquivalentConstraint( IEnumerable other )

Syntax
Is.EquivalentTo( IEnumerable other )

Examples of Use
int[] 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 ) );
Notes

   1. To compare collections for equality, use Is.EqualTo().

CollectionSubsetConstraint

Action

Tests that one collection is a subset of another.

Constructor
CollectionSubsetConstraint( ICollection )

Syntax
Is.SubsetOf( IEnumerable )

Example of Use
int[] iarray = new int[] { 1, 2, 3 };

Assert.That( new int[] { 1, 3 }, Is.SubsetOf( iarray ) );

CollectionOrderedConstraint (NUnit 2.5)

Action

Tests that a collection is ordered.

Constructor
CollectionOrderedConstraint()

Syntax
Is.Ordered

Modifiers
...Descending
...By(string propertyName)
...Using(IComparer comparer)
...Using(IComparer<T> comparer)
...Using(Comparison<T> comparer)

Examples of Use
int[] 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");
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                          Operation
Has.Property( string )    PropertyConstraint( string ) tests that a specific property exists
Has.Property( string,     PropertyConstraint( string, tests that the value of a property is equal
object )                  object )                     to the value provided
Has.Property( string,                                  applies the following constraint to the
                          PropertyConstraint
Constraint)...                                         value of a named property
                                                       tests that the object's Length property is
Has.Length( int )         PropertyConstraint
                                                       equal to the value given
                                                       tests that the object's Count property is
Has.Count( int )          PropertyConstraint
                                                       equal to the value given

Throws Constraint (NUnit 2.5)
ThrowsConstraint is used to test that some code, represented as a delegate, throws a particular
exception. It may be used alone, to merely test the type of constraint, or with an additional
constraint to be applied to the exception specified as an argument. p>The related
ThrowsNothingConstraint simply asserts that the delegate does not throw an exception.

Constructors
ThrowsConstraint(Type expectedType)
ThrowsConstraint<T>()
ThrowsConstraint(Type expectedType, Constraint constraint)
ThrowsConstraint<T>(Constraint constraint)
ThrowsNothingConstraint()

Syntax
Throws.Exception
Throws.TargetInvocationException
Throws.ArgumentException
Throws.InvalidOperationException
Throws.TypeOf(Type expectedType)
Throws.TypeOf<T>()
Throws.InstanceOf(Type expectedType)
Throws.InstanceOf<T>()
Throws.Nothing
Throws.InnerException
Examples of Use
// .NET 1.1
Assert.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.0
Assert.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                               Operation

Is.Not...           NotConstraint( Constraint )       Negates or reverses the effect of a constraint
Tests that all members of a collection match
Is.All...            AllItemsConstraint( Constraint )
                                                        the constraint

Constraint &         AndConstraint( Constraint,
                                                        Tests that both of the constraints are met
Constraint           Constraint )

Constraint |         OrConstraint( Constraint,
                                                        Tests that at least one of the constraints is met
Constraint           Constraint )


Examples of Use
Assert.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 inheritance
Expect( 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 time
has passed. In it's 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 expression
up to the point where After appears.

Use of a DelayedConstraint with a value argument makes no sense, since the value will be
extracted at the point of call. It's intended use is with delegates and references. If a delegate is
used with polling, it may be called multiple times so only methods without side effects should be
used in this way.

   Syntax
                           Constructor                                    Operation
   Helper
After(int)      DelayedConstraint(Constraint, int) tests that a constraint is satisfied after a delay.
                DelayedConstraint(Constraint, int, tests that a constraint is satisfied after a delay
After(int, int)
                int)                               using polling.

List Mapper (NUnit 2.4.2)
Unlike Constraint classes, ListMapper is used to modify the actual value argument to
Assert.That(). It transforms the actual value, which must be a collection, creating a new
collection to be tested against the supplied constraint. Currently, ListMapper supports one
transformation: creating a collection of property values.
Normally, ListMapper will be used through the List.Map() syntax helper or the inherited syntax
equivalent, 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 AssertionHelper
Expect(Map(strings).Property("Length"), EqualTo(lengths));


ReusableConstraint (NUnit 2.5.6)
Normally constraints just work. However, attempting to reuse the same constraint in several
places 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! What's that about?

We'll 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); // Passes
Or alternatively..

     var myConstraint = new ReusableConstraint(Is.Not.Null);
     Assert.That("not a null", myConstraint); // Passes
     Assert.That("not a null", myConstraint); // Passes

Technical Explanation

In the original example, the value assigned to myConstraint is known as an unresolved
constraint. In fact, it's an unresolved NullConstraint, because that was the last constraint
encountered in the expression. It's associated with a Not operator that has not yet been applied.

That's OK for use with Assert.That(), because the method knows how to resolve a constraint
before using it. Assert.That() resolves this constraint to a NotConstraint referencing the original
NullConstraint.

Of course, the original reference in myConstraint is left unchanged in all of this. But the
EqualConstraint it points to has now been resolved. It is now a resolved constraint and can't be
resolved again by the second Assert.That(), which only sees the NullConstraint and not the
NotConstraint.

So, for reusability, what we want to save is the result of resolving the constraint, in this case

     NotConstraint => NullConstraint
That's what ReusableConstraint does for us. It resolves the full expression and saves the result. Then it
passes all operations on to that saved result.

When to Use It

Use this constraint any time you want to reuse a constraint expression and you'll be safe.

If you like to take chances, you'll 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.

Attributes
Version 1 of NUnit used the classic approach to identifying tests based on inheritance and
naming 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 use
inheritance in other ways. And because there is no arbitrary convention for naming tests, the
choice 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 that
contains tests must include a using statement for that namespace and the project must reference
the framework assembly, nunit.framework.dll.

Beginning with NUnit 2.4.6, NUnit's attributes are no longer sealed and any attributes that derive
from them will be recognized by NUnit.
CategoryAttribute (NUnit 2.2)

The Category attribute provides an alternative to suites for dealing with groups of tests. Either
individual test cases or fixtures may be identified as belonging to a particular category. Both the
gui and console test runners allow specifying a list of categories to be included in or excluded
from 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 and
through a separate "Categories" tab in the gui. The gui provides a visual indication of which
categories are selected at any time.

Test Fixture Syntax


namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;

  [TestFixture]
  [Category("LongRunning")]
  public class LongRunningTests
  {
    // ...
  }
}
Imports System
Imports Nunit.Framework

Namespace Nunit.Tests

  <TestFixture(), Category("LongRunning")>
  Public Class LongRunningTests
    ' ...
  End Class
End Namespace
#using <Nunit.Framework.dll>
using namespace System;
using namespace NUnit::Framework;

namespace NUnitTests
{
  [TestFixture]
  [Category("LongRunning")]
  public __gc class LongRunningTests
  {
     // ...
  };
}

#include "cppsample.h"
namespace NUnitTests {
  // ...
}
package NUnit.Tests;

import System.*;
import NUnit.Framework.TestFixture;


/** @attribute NUnit.Framework.TestFixture() */
/** @attribute NUnit.Framework.Category("LongRunning") */
public class LongRunningTests
{
  // ...
}

Test Syntax


namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;

  [TestFixture]
  public class SuccessTests
  {
    [Test]
    [Category("Long")]
    public void VeryLongTest()
    { /* ... */ }
}
Imports System
Imports Nunit.Framework

Namespace Nunit.Tests

  <TestFixture()>
  Public Class SuccessTests
    <Test(), Category("Long")> Public Sub VeryLongTest()
      ' ...
    End Sub
  End Class
End Namespace
#using <Nunit.Framework.dll>
using namespace System;
using namespace NUnit::Framework;

namespace NUnitTests
{
  [TestFixture]
  public __gc class SuccessTests
  {
     [Test][Category("Long")] void VeryLongTest();
  };
}
#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 Attributes

Beginning with NUnit 2.4, it is possible to define custom attributes that derive from
CategoryAttribute and have them recognized by NUnit. The default protected constructor of
CategoryAttribute sets the category name to the name of your class.

Here's 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 provide
special 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 cases
for 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.

Example

The following test will be executed six times, as follows:

          MyTest(1, "A")
          MyTest(1, "B")
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 does
not affect the culture setting, but merely uses it to determine whether to run the test. If you wish
to 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 node
for 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 may
specify either specific cultures, like "en-GB" or neutral cultures like "de".

Test Fixture Syntax


namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;

  [TestFixture]
  [Culture("fr-FR")]
  public class FrenchCultureTests
  {
    // ...
  }
}
Imports System
Imports Nunit.Framework

Namespace Nunit.Tests

  <TestFixture(), Culture("fr-FR")>
  Public Class FrenchCultureTests
    ' ...
  End Class
End Namespace
#using <Nunit.Framework.dll>
using namespace System;
using namespace NUnit::Framework;
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 Syntax


namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;

  [TestFixture]
  public class SuccessTests
  {
    [Test]
    [Culture(Exclude="en,de")]
    public void SomeTest()
    { /* ... */ }
}
Imports System
Imports Nunit.Framework

Namespace Nunit.Tests

  <TestFixture()>
  Public Class SuccessTests
    <Test(), Culture(Exclude="en,de")> Public Sub SomeTest()
      ' ...
    End Sub
  End Class
End Namespace
#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 ignored
for ordinary tests - including tests with parameters.

DataPointAttribute

When a Theory is loaded, NUnit creates arguments for each of its parameters by using any fields
of the same type as the parameter annotated with the DatapointAttribute. Fields must be
members of the class containing the Theory and their Type must exactly match the argument for
which data is being supplied.

DataPointsAttribute

In addition to specifying individual datapoints, collections of datapoints may be provided by use
of the DatapointsAttribute - note the spelling. This attribute may be placed on methods or
properties 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 required
type. The data Type must exactly match the argument for which data is being supplied.
Automatically Supplied Datapoints

It is normally not necessary to specify datapoints for boolean or enum arguments. Beginning
with version 2.5.4, NUnit automatically supplies values of true and false for boolean arguments
and will supply all defined values of any enumeration.

If for some reason you don't wish to use all possible values, you can override this behavior by
supplying your own datapoints. If you supply any datapoints for an argument, automatic
datapoint 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 System
Imports Nunit.Framework

Namespace Nunit.Tests

  <TestFixture(), Description("Fixture description here")>_
  Public Class SomeTests
    <Test(), Description("Test description here")>_
    Public Sub OneTest()
    ' ...
    End Sub
  End Class
End Namespace
[assembly:Description("Assembly description here")]

#using <Nunit.Framework.dll>
using namespace System;
using namespace NUnit::Framework;
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 Description
attribute 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 a
number of positional and named parameters, which we will discuss in separate sections
according to the purpose they serve.

Specifying the Expected Exception Type

The original attribute, introduced with NUnit 2.0 took a single argument giving the exact type of
the expected exception. For example...

[ExpectedException( typeof( ArgumentException ) )]
public void TestMethod()
{
...
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.Argument
exception is thrown.

Specifying the Expected Message

NUnit 2.1 introduced a constructor with a second argument, specifying the exact text of the
message property of the exception. After NUnit 2.2.4, the same extension was made to the
constructor taking a string argument. With NUnit 2.4, these arguments are marked obsolete, and
a named parameter is provided instead...

// Obsolete form:
[ExpectedException( typeof( ArgumentException ), "expected message" )]
[ExpectedException( "System.ArgumentException", "expected message" )]

// Prefered form:
[ExpectedException( typeof( ArgumentException ), ExpectedMessage="expected
message" )]
[ExpectedException( "System.ArgumentException", ExpectedMessage="expected
message" )]

With NUnit 2.4, it is possible to specify additional tests on the exception message, beyond a
simple exact match. This is done using the MatchType named parameter, whose argument is an
enumeration, 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 message
containing "unspecified" is received.

[ExpectedException( typeof( ArgumentException),
ExpectedMessage="unspecified", MatchType=MessageMatch.Contains )]
public void TestMethod()
{
...

If MatchType is not specified, an exact match is used as before.

Specifying a Custom Error Message

With NUnit 2.4, it is possible to specify a custom message to be displayed if the
ExpectedException attribute is not satisfied. This is done through the UserMessage named
parameter...

[ExpectedException( typeof( ArgumentException ), UserMessage="Custom message"
)]
public void TestMethod()
{
...

Handling the Exception in Code

If 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 is
particularly useful when multiple exceptions need to be processed in the same way.

An common exception handler may be designated by implementing the
IExpectExceptionInterface, 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 may
be 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 )
{
...
}
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 normal
exception handler applies to any other methods that specify an ExpectedException.

However it is specified, the handler method should examine the exception and Assert on
whatever properties are relevant. Any resulting failure message will then be consistent in format
with 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 System
Imports Nunit.Framework

Namespace 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 Class
End Namespace
#using <Nunit.Framework.dll>
using namespace System;
using namespace NUnit::Framework;

namespace NUnitTests
{
[TestFixture]
    public __gc class SuccessTests
    {
      [Test]
      [ExpectedException(__typeof(InvalidOperationException))]
      void ExpectAnExceptionByType();

         [Test]
         [ExpectedException(S"SystemInvalidOperationException")]
         void ExpectAnExceptionByName();
    };
}

#include "cppsample.h"

namespace NUnitTests {
  // ...
}

ExplicitAttribute (NUnit 2.2)

The Explicit attribute causes a test or test fixture to be ignored unless it is explicitly selected for
running. The test or fixture will be run if it is selected in the gui, if its name is specified on the
console runner command line as the fixture to run or if it is included by use of a Category filter.

An optional string argument may be used to give the reason for marking the test Explicit.

If a test or fixture with the Explicit attribute is encountered in the course of running tests, it is
skipped unless it has been specifically selected by one of the above means. The test does not
affect the outcome of the run at all: it is not considered as ignored and is not even counted in the
total number of tests. In the gui, the tree node for the test remains gray and the status bar color is
not affected.

Note: In versions of NUnit prior to 2.4, these tests were shown as ignored.

Test Fixture Syntax


namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;

    [TestFixture, Explicit]
    public class ExplicitTests
    {
      // ...
    }
}
Imports System
Imports Nunit.Framework

Namespace Nunit.Tests
<TestFixture(), Explicit()>
  Public Class ExplicitTests
    ' ...
  End Class
End Namespace
#using <Nunit.Framework.dll>
using namespace System;
using namespace NUnit::Framework;

namespace NUnitTests
{
  [TestFixture]
  [Explicit]
  public __gc class ExplicitTests
  {
     // ...
  };
}

#include "cppsample.h"

namespace NUnitTests {
  // ...
}
package NUnit.Tests;

import System.*;
import NUnit.Framework.TestFixture;


/** @attribute NUnit.Framework.TestFixture() */
/** @attribute NUnit.Framework.Explicit() */
public class ExplicitTests
{
  // ...
}

Test Syntax


namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;

  [TestFixture]
  public class SuccessTests
  {
    [Test, Explicit]
    public void ExplicitTest()
    { /* ... */ }
}
Imports System
Imports Nunit.Framework
Namespace Nunit.Tests

  <TestFixture()>
  Public Class SuccessTests
    <Test(), Explicit()> Public Sub ExplicitTest()
      ' ...
    End Sub
  End Class
End Namespace
#using <Nunit.Framework.dll>
using namespace System;
using namespace NUnit::Framework;

namespace NUnitTests
{
  [TestFixture]
  public __gc class SuccessTests
  {
     [Test][Explicit] void ExplicitTest();
  };
}

#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.Explicit() */
  public void ExplicitTest()
  { /* ... */ }
}

IgnoreAttribute (NUnit 2.0)

The ignore attribute is an attribute to not run a test or test fixture for a period of time. The person
marks either a Test or a TestFixture with the Ignore Attribute. The running program sees the
attribute and does not run the test or tests. The progress bar will turn yellow if a test is not run
and the test will be mentioned in the reports that it was not run.

This feature should be used to temporarily not run a test or fixture. This is a better mechanism
than commenting out the test or renaming methods, since the tests will be compiled with the rest
of the code and there is an indication at run time that a test is not being run. This insures that
tests will not be forgotten.
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

Contenu connexe

Tendances

Tendances (20)

Junit
JunitJunit
Junit
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 
A04
A04A04
A04
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
 
JSpiders - Wrapper classes
JSpiders - Wrapper classesJSpiders - Wrapper classes
JSpiders - Wrapper classes
 
Generics C#
Generics C#Generics C#
Generics C#
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java unit i
Java unit iJava unit i
Java unit i
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 

Similaire à What Do You Mean By NUnit

Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnitAktuğ Urun
 
AN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATION
AN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATIONAN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATION
AN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATIONecij
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest modulePyCon Italia
 
What is a constructorAns)A constructor is also type of method whi.pdf
What is a constructorAns)A constructor is also type of method whi.pdfWhat is a constructorAns)A constructor is also type of method whi.pdf
What is a constructorAns)A constructor is also type of method whi.pdfanandanand521251
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object javamha4
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.comDavisMurphyB81
 
Introduction to System verilog
Introduction to System verilog Introduction to System verilog
Introduction to System verilog Pushpa Yakkala
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com donaldzs157
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 

Similaire à What Do You Mean By NUnit (20)

Junit basics
Junit basicsJunit basics
Junit basics
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
AN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATION
AN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATIONAN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATION
AN ENVIRONMENT FOR NON-DUPLICATE TEST GENERATION FOR WEB BASED APPLICATION
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
 
What is a constructorAns)A constructor is also type of method whi.pdf
What is a constructorAns)A constructor is also type of method whi.pdfWhat is a constructorAns)A constructor is also type of method whi.pdf
What is a constructorAns)A constructor is also type of method whi.pdf
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
Introduction to System verilog
Introduction to System verilog Introduction to System verilog
Introduction to System verilog
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 

Plus de Anand Kumar Rajana (13)

Interface Vs Abstact
Interface Vs AbstactInterface Vs Abstact
Interface Vs Abstact
 
Anand's Leadership Assessment
Anand's Leadership AssessmentAnand's Leadership Assessment
Anand's Leadership Assessment
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
 
Wcf
WcfWcf
Wcf
 
Sql Server 2012 Installation..
Sql Server 2012 Installation..Sql Server 2012 Installation..
Sql Server 2012 Installation..
 
Json
JsonJson
Json
 
Jquery Ajax
Jquery AjaxJquery Ajax
Jquery Ajax
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
J Query Introduction And JQuery Selectors
J Query Introduction And JQuery SelectorsJ Query Introduction And JQuery Selectors
J Query Introduction And JQuery Selectors
 

What Do You Mean By NUnit

  • 1. What Is NUnit? NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit, the current production release, version 2.5, is the sixth major release of this xUnit based unit testing tool for Microsoft .NET. It is written entirely in C# and has been completely redesigned to take advantage of many .NET language features, for example custom attributes and other 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 .NET language 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 you write 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 NUnit tools 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 Assert class. 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 • TestFixtureTearDown Add References in Project Browse references from C:Program FilesNUnit 2.5.2binnet-2.0framework i.e. nunit.framework.dll Assertions
  • 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 contains multiple assertions, any that follow the one that failed will not be executed. For this reason, it's usually best to try for one assertion per test. Each method may be called without a message, with a simple text message or with a message and arguments. In the last case the message is formatted using the provided text and arguments. Two Models Before 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 people prefer it. Beginning with NUnit 2.4, a new "Constraint-based" model was introduced. This approach uses a single method of the Assert class for all assertions, passing a Constraint object that specifies the test to be performed. This constraint-based model is now used internally by NUnit for all assertions. The methods of the classic approach have been re-implemented on top of this new model. Equality Asserts These methods test whether the two arguments are equal. Overloaded methods are provided for common value types so that languages that don't automatically box values can use them directly. Comparing Numerics of Different Types The method overloads that compare two objects make special provision so that numeric values of different types compare as expected. This assert succeeds: Assert.AreEqual( 5, 5.0 ); Comparing Floating Point Values Values of type float and double are normally compared using an additional argument that indicates 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 not provided. In earlier versions, or if the default has not been set, values are tested for exact equality. Special values are handled so that the following Asserts succeed: Assert.AreEqual ( double.PositiveInfinity, double.PositiveInfinity );
  • 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 would fail. We have made this change because the new behavior seems to be more useful in tests. To avoid confusion, we suggest using the new Assert.IsNaN method where appropriate. Comparing Arrays and Collections Since version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginning with version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections may be compared. Two arrays or collections will be treated as equal by Assert.AreEqual if they have the same dimensions and if each of the corresponding elements is equal. Identity Asserts Assert.AreSame and Assert.AreNotSame test whether the same objects are referenced by the two 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 Asserts Methods that test a specific condition are named for the condition they test and take the value tested as their first argument and, optionally a message as the second. The following methods are provided: 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. 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 are compatible with earlier versions of the NUnit framework, while those without "Is" are provided for compatibility with NUnitLite. Assert.IsEmpty and Assert.IsNotEmpty may be used to test either a string or a collection.
  • 5. Comparisons (NUnit 2.2.4) The following methods test whether one object is greater than than another. Contrary to the normal order of Asserts, these methods are designed to be read in the "natural" English-language or 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 to the normal order of Asserts, these methods are designed to be read in the "natural" English-
  • 6. language or mathematical order. Thus Assert.GreaterOrEqual( x, y ) asserts that x is greater than 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 normal order of Asserts, these methods are designed to be read in the "natural" English-language or mathematical 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. 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 the normal order of Asserts, these methods are designed to be read in the "natural" English-language or 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. 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. 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, it attempts to invoke a code snippet, represented as a delegate, in order to verify that it throws a particular exception. It's also in a class by itself in that it returns an Exception, rather than void, if the Assert is successful. 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 exception thrown, 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 the one 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. 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 to execute the code in question. Under .NET 2.0, this may be an anonymous delegate. If compiling under 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. 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 Types When used with a Type argument, Assert.Throws requires that exact type to be thrown. If you want 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 allowing derived 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 type Assert.Throws( Is.InstanceOf( typeof(ApplicationException), code ); Assert.Throws( Is.InstanceOf<ApplicationException>(), code ); // Allow both ApplicationException and any derived type Assert.Catch<ApplicationException>( code );
  • 12. // Allow any kind of exception Assert.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. Here's 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. 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. 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 actual 89. 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 actual 95. 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 actual 101. 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 actual 114. 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. 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 as Streams, 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. 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 for equality. 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. 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 specified directory 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 second directory 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. 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. The logic necessary to carry out each assertion is embedded in the constraint object passed as the second parameter to that method. Here's a very simple assert using the constraint model: Assert.That( myString, Is.EqualTo("Hello") ); The second argument in this assertion uses one of NUnit's syntax helpers to create an EqualConstraint. 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. 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 in place 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 IConstraint interface, which supports performing a test on an actual value and generating appropriate messages. This interface is described in more detail under Custom Constraints. NUnit provides a number of constraint classes similar to the EqualConstraint used in the example above. Generally, these classes may be used directly or through a syntax helper. Test fixture classes inheriting from AssertionHelper are able to use shorter forms. The valid forms are described on the pages related to each constraint. Note that the menu items listed to the right generally 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 value supplied in its constructor, optionally within a specified tolerance. Constructor EqualConstraint(object expected )
  • 20. Syntax Is.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 Numerics Numerics are compared based on their values. Different types may be compared successfully if their values are equal. Using the Within modifier, numerics may be tested for equality within a fixed or percent tolerance. 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 Values Values of type float and double are normally compared using a tolerance specified by the Within modifier. The special values PositiveInfinity, NegativeInfinity and NaN compare as equal to themselves. With version 2.5, floating-point values may be compared using a tolerance in "Units in the Last Place" or ULPs. For certain types of numerical work, this is safer than a fixed tolerance because it 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. 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 Strings String comparisons normally respect case. The IgnoreCase modifier causes the comparison to be 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 TimeSpans DateTimes and TimeSpans may be compared either with or without a tolerance. A tolerance is specified using Within with either a TimeSpan as an argument or with a numeric value followed 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 Collections Since version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginning with version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections may be compared. With version 2.5, any IEnumerable is supported. Two arrays, collections or IEnumerables are considered equal if they have the the same dimensions and if each of the corresponding elements is equal. If you want to treat two arrays of different shapes as simple collections for purposes of comparison, use the AsCollection modifier, which causes the comparison to be made element by element, without regard for the rank or dimensions of the array. Note that jagged arrays (arrays of arrays) do not have a single underlying collection. The modifier would be applied to each array 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. 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 Dictionaries Dictionaries 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 order for 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. Two dictionaries 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 and non-generic dictionaries (Hashtables) may be successfully compared. User-Specified Comparers If the default NUnit or .NET behavior for testing equality doesn't meet your needs, you can supply 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. 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 same identity as the object supplied in its constructor. Constructor SameAsConstraint( object expected ) Syntax Is.SameAs( object expected ) Examples of Use Exception 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. They verify that the actual value satisfies the condition. The following condition helpers are provided. NullConstraint Action Tests that a value is Null. Constructor NullConstraint()
  • 24. Syntax Is.Null Examples of Use Assert.That( anObject, Is.Null ); Assert.That( anObject, Is.Not.Null ); TrueConstraint Action Tests that a value is true. Constructor TrueConstraint() Syntax Is.True Example of Use Assert.That( condition, Is.True ); FalseConstraint Action Tests that a value is false. Constructor FalseConstraint() Syntax Is.False Example of Use Assert.That( condition, Is.False ); NaNConstraint Action Tests that a value is floating-point NaN. Constructor NaNConstraint() Syntax Is.NaN Examples of Use Assert.That( aDouble, Is.NaN );
  • 25. Assert.That( aDouble, Is.Not.NaN ); EmptyConstraint Action Tests that an object is an empty string, directory or collection. Constructor EmptyConstraint() Syntax Is.Empty Examples of Use Assert.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. UniqueItemsConstraint Action Tests that an array, collection or other IEnumerable is composed of unique items with no duplicates. Constructor UniqueItemsConstraint() Syntax Is.Unique Example of Use Assert.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 the IComparable interface or - beginning with NUnit 2.5 - IComparable<T>.
  • 26. Beginning with NUnit 2.5, you may supply your own comparison algorithm through the Using modifier. GreaterThanConstraint Action Tests that one value is greater than another. Constructor GreaterThanConstraint(object expected) Syntax Is.GreaterThan(object expected) Modifiers ...Using(IComparer comparer) ...Using(IComparer<T> comparer) ...Using(Comparison<T> comparer) Examples of Use Assert.That(7, Is.GreaterThan(3)); Assert.That(myOwnObject, Is.GreaterThan(theExpected).Using(myComparer)); GreaterThanOrEqualConstraint Action Tests that one value is greater than or equal to another. Constructor GreaterThanOrEqualConstraint(object expected) Syntax Is.GreaterThanOrEqualTo(object expected) Is.AtLeast(object expected) Modifiers ...Using(IComparer comparer) ...Using(IComparer<T> comparer) ...Using(Comparison<T> comparer) Examples of Use Assert.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. LessThanConstraint Action Tests that one value is less than another. Constructor LessThanConstraint(object expected) Syntax Is.LessThan(object expected) Modifiers ...Using(IComparer comparer) ...Using(IComparer<T> comparer) ...Using(Comparison<T> comparer) Examples of Use Assert.That(3, Is.LessThan(7)); Assert.That(myOwnObject, Is.LessThan(theExpected).Using(myComparer)); LessThanOrEqualConstraint Action Tests that one value is less than or equal to another. Constructor LessThanOrEqualConstraint(object expected) Syntax Is.LessThanOrEqualTo(object expected) Is.AtMost(object expected) Modifiers ...Using(IComparer comparer) ...Using(IComparer<T> comparer) ...Using(Comparison<T> comparer) Examples of Use Assert.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. RangeConstraint Action Constructor RangeConstraint(IComparable from, IComparable to) Syntax Is.InRange(IComparable from, IComparable to) Modifiers ...Using(IComparer comparer) ...Using(IComparer<T> comparer) ...Using(Comparison<T> comparer) Examples of Use int[] 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. This allows testing paths that are created by an application for reference or later use, without any effect on the environment. Path constraints are intended to work across multiple file systems, and convert paths to a canonical form before comparing them. It is usually not necessary to know the file system of the paths in order to compare them. Where necessary, the programmer may use the IgnoreCase and RespectCase modifiers to provide behavior other than the system default. SamePathConstraint Action Tests that two paths are equivalent. Constructor SamePathConstraint( string expectedPath ) Syntax Is.SamePath( string expectedPath ) Modifiers ...IgnoreCase
  • 29. ...RespectCase Examples of Use Assert.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 ); SamePathOrUnderConstraint Action Tests that one path is equivalent another path or that it is under it. Constructor SamePathOrUnderConstraint( string expectedPath ) Syntax Is.SamePathOrUnder( string expectedPath ) Modifiers ...IgnoreCase ...RespectCase Examples of Use Assert.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 are provided: Syntax Helper Constructor Operation Is.TypeOf( Type ) ExactTypeConstraint( Type ) tests that an object is an exact Type
  • 30. InstanceOfTypeConstraint( Type Is.InstanceOfType( Type ) tests that an object is an instance of a Type ) Is.AssignableFrom( Type AssignableFromConstraint( Type tests that one type is assignable from ) ) another Examples of Use Assert.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 inheritance Expect( 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 value with 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. SubstringConstraint Action Tests for a substring. Constructor SubstringConstraint(string expected) Syntax Is.StringContaining(string expected) Contains.Substring(string expected) ContainsSubstring(string expected) Contains(string expected) [Obsolete] Text.Contains(string expected) [Obsolete] Text.DoesNotContain(string expected) Modifiers ...IgnoreCase Examples of Use string phrase = "Make your tests fail before passing!"
  • 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. StartsWithConstraint Action Tests for an initial string. Constructor StartsWithConstraint(string expected) Syntax Is.StringStarting(string expected) StartsWith(string expected) [Obsolete] Text.StartsWith(string expected) [Obsolete] Text.DoesNotStartWith(string expected) Modifiers ...IgnoreCase Examples of Use string 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. EndsWithConstraint Action Tests for an ending string.
  • 32. Constructor EndsWithConstraint(string expected) Syntax Is.StringEnding(string expected) EndsWith(string expected) [Obsolete] Text.EndsWith(string expected) [Obsolete] Text.DoesNotEndWith(string expected) Modifiers ...IgnoreCase Examples of Use string 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. RegexConstraint Action Tests that a pattern is matched. Constructor RegexConstraint(string pattern) Syntax Is.StringMatching(string pattern) Matches(string pattern) [Obsolete] Text.Matches(string pattern) [Obsolete] Text.DoesNotMatch(string pattern) Modifiers ...IgnoreCase Examples of Use string 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. 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 collection constraints 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 releases give 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 second would have succeeded in earlier versions of NUnit. int[] iarray = new int[] { 1, 2, 3 }; Assert.That( 5, Is.SubsetOf( iarray ) ); // Fails in early releases Assert.That( 5, Is.Not.SubsetOf( iarray ) ); / AllItemsConstraint Action Applies a constraint to each item in a collection, succeeding only if all of them succeed. Constructor AllItemsConstraint(Constraint itemConstraint) Syntax Is.All... Has.All... Examples of Use int[] 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) ); SomeItemsConstraint Action Applies a constraint to each item in a collection, succeeding if at least one of them succeeds.
  • 34. Constructor SomeItemsConstraint(Constraint itemConstraint) Syntax Has.Some... Examples of Use int[] 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) ); NoItemConstraint Action Applies a constraint to each item in a collection, succeeding only if all of them fail. Constructor NoItemConstraint(Constraint itemConstraint) Syntax Has.None... Has.No... Examples of Use int[] 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) ); UniqueItemsConstraint Action Tests that a collection contains only unique items. Constructor UniqueItemsConstraint() Syntax Is.Unique Example of Use string[] sarray = new string[] { "a", "b", "c" }; Assert.That( sarray, Is.Unique );
  • 35. Notes 1. ?? CollectionContainsConstraint Action Tests that a collection contains an object. Constructor CollectionContainsConstraint( object ) Syntax Has.Member( object ) Contains.Item( object ) Examples of Use int[] 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(...). CollectionEquivalentConstraint Action Tests that two collections are equivalent - that they contain the same items, in any order. Constructor CollectionEquivalentConstraint( IEnumerable other ) Syntax Is.EquivalentTo( IEnumerable other ) Examples of Use int[] 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. Notes 1. To compare collections for equality, use Is.EqualTo(). CollectionSubsetConstraint Action Tests that one collection is a subset of another. Constructor CollectionSubsetConstraint( ICollection ) Syntax Is.SubsetOf( IEnumerable ) Example of Use int[] iarray = new int[] { 1, 2, 3 }; Assert.That( new int[] { 1, 3 }, Is.SubsetOf( iarray ) ); CollectionOrderedConstraint (NUnit 2.5) Action Tests that a collection is ordered. Constructor CollectionOrderedConstraint() Syntax Is.Ordered Modifiers ...Descending ...By(string propertyName) ...Using(IComparer comparer) ...Using(IComparer<T> comparer) ...Using(Comparison<T> comparer) Examples of Use int[] 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. 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 Operation Has.Property( string ) PropertyConstraint( string ) tests that a specific property exists Has.Property( string, PropertyConstraint( string, tests that the value of a property is equal object ) object ) to the value provided Has.Property( string, applies the following constraint to the PropertyConstraint Constraint)... value of a named property tests that the object's Length property is Has.Length( int ) PropertyConstraint equal to the value given tests that the object's Count property is Has.Count( int ) PropertyConstraint equal to the value given Throws Constraint (NUnit 2.5) ThrowsConstraint is used to test that some code, represented as a delegate, throws a particular exception. It may be used alone, to merely test the type of constraint, or with an additional constraint to be applied to the exception specified as an argument. p>The related ThrowsNothingConstraint simply asserts that the delegate does not throw an exception. Constructors ThrowsConstraint(Type expectedType) ThrowsConstraint<T>() ThrowsConstraint(Type expectedType, Constraint constraint) ThrowsConstraint<T>(Constraint constraint) ThrowsNothingConstraint() Syntax Throws.Exception Throws.TargetInvocationException Throws.ArgumentException Throws.InvalidOperationException Throws.TypeOf(Type expectedType) Throws.TypeOf<T>() Throws.InstanceOf(Type expectedType) Throws.InstanceOf<T>() Throws.Nothing Throws.InnerException
  • 38. Examples of Use // .NET 1.1 Assert.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.0 Assert.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 Operation Is.Not... NotConstraint( Constraint ) Negates or reverses the effect of a constraint
  • 39. Tests that all members of a collection match Is.All... AllItemsConstraint( Constraint ) the constraint Constraint & AndConstraint( Constraint, Tests that both of the constraints are met Constraint Constraint ) Constraint | OrConstraint( Constraint, Tests that at least one of the constraints is met Constraint Constraint ) Examples of Use Assert.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 inheritance Expect( 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 time has passed. In it's 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 expression up to the point where After appears. Use of a DelayedConstraint with a value argument makes no sense, since the value will be extracted at the point of call. It's intended use is with delegates and references. If a delegate is used with polling, it may be called multiple times so only methods without side effects should be used in this way. Syntax Constructor Operation Helper After(int) DelayedConstraint(Constraint, int) tests that a constraint is satisfied after a delay. DelayedConstraint(Constraint, int, tests that a constraint is satisfied after a delay After(int, int) int) using polling. List Mapper (NUnit 2.4.2) Unlike Constraint classes, ListMapper is used to modify the actual value argument to Assert.That(). It transforms the actual value, which must be a collection, creating a new collection to be tested against the supplied constraint. Currently, ListMapper supports one transformation: creating a collection of property values.
  • 40. Normally, ListMapper will be used through the List.Map() syntax helper or the inherited syntax equivalent, 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 AssertionHelper Expect(Map(strings).Property("Length"), EqualTo(lengths)); ReusableConstraint (NUnit 2.5.6) Normally constraints just work. However, attempting to reuse the same constraint in several places 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! What's that about? We'll 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); // Passes Or alternatively.. var myConstraint = new ReusableConstraint(Is.Not.Null); Assert.That("not a null", myConstraint); // Passes Assert.That("not a null", myConstraint); // Passes Technical Explanation In the original example, the value assigned to myConstraint is known as an unresolved constraint. In fact, it's an unresolved NullConstraint, because that was the last constraint encountered in the expression. It's associated with a Not operator that has not yet been applied. That's OK for use with Assert.That(), because the method knows how to resolve a constraint before using it. Assert.That() resolves this constraint to a NotConstraint referencing the original NullConstraint. Of course, the original reference in myConstraint is left unchanged in all of this. But the EqualConstraint it points to has now been resolved. It is now a resolved constraint and can't be
  • 41. resolved again by the second Assert.That(), which only sees the NullConstraint and not the NotConstraint. So, for reusability, what we want to save is the result of resolving the constraint, in this case NotConstraint => NullConstraint That's what ReusableConstraint does for us. It resolves the full expression and saves the result. Then it passes all operations on to that saved result. When to Use It Use this constraint any time you want to reuse a constraint expression and you'll be safe. If you like to take chances, you'll 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. Attributes Version 1 of NUnit used the classic approach to identifying tests based on inheritance and naming 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 use inheritance in other ways. And because there is no arbitrary convention for naming tests, the choice 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 that contains tests must include a using statement for that namespace and the project must reference the framework assembly, nunit.framework.dll. Beginning with NUnit 2.4.6, NUnit's attributes are no longer sealed and any attributes that derive from them will be recognized by NUnit.
  • 42. CategoryAttribute (NUnit 2.2) The Category attribute provides an alternative to suites for dealing with groups of tests. Either individual test cases or fixtures may be identified as belonging to a particular category. Both the gui and console test runners allow specifying a list of categories to be included in or excluded from 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 and through a separate "Categories" tab in the gui. The gui provides a visual indication of which categories are selected at any time. Test Fixture Syntax namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] [Category("LongRunning")] public class LongRunningTests { // ... } } Imports System Imports Nunit.Framework Namespace Nunit.Tests <TestFixture(), Category("LongRunning")> Public Class LongRunningTests ' ... End Class End 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. namespace NUnitTests { // ... } package NUnit.Tests; import System.*; import NUnit.Framework.TestFixture; /** @attribute NUnit.Framework.TestFixture() */ /** @attribute NUnit.Framework.Category("LongRunning") */ public class LongRunningTests { // ... } Test Syntax namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Category("Long")] public void VeryLongTest() { /* ... */ } } Imports System Imports Nunit.Framework Namespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Category("Long")> Public Sub VeryLongTest() ' ... End Sub End Class End 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. #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 Attributes Beginning with NUnit 2.4, it is possible to define custom attributes that derive from CategoryAttribute and have them recognized by NUnit. The default protected constructor of CategoryAttribute sets the category name to the name of your class. Here's 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 provide special 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 cases for 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. Example The following test will be executed six times, as follows: MyTest(1, "A") MyTest(1, "B")
  • 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 does not affect the culture setting, but merely uses it to determine whether to run the test. If you wish to 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 node for 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 may specify either specific cultures, like "en-GB" or neutral cultures like "de". Test Fixture Syntax namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] [Culture("fr-FR")] public class FrenchCultureTests { // ... } } Imports System Imports Nunit.Framework Namespace Nunit.Tests <TestFixture(), Culture("fr-FR")> Public Class FrenchCultureTests ' ... End Class End Namespace #using <Nunit.Framework.dll> using namespace System; using namespace NUnit::Framework;
  • 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 Syntax namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Culture(Exclude="en,de")] public void SomeTest() { /* ... */ } } Imports System Imports Nunit.Framework Namespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Culture(Exclude="en,de")> Public Sub SomeTest() ' ... End Sub End Class End Namespace
  • 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 ignored for ordinary tests - including tests with parameters. DataPointAttribute When a Theory is loaded, NUnit creates arguments for each of its parameters by using any fields of the same type as the parameter annotated with the DatapointAttribute. Fields must be members of the class containing the Theory and their Type must exactly match the argument for which data is being supplied. DataPointsAttribute In addition to specifying individual datapoints, collections of datapoints may be provided by use of the DatapointsAttribute - note the spelling. This attribute may be placed on methods or properties 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 required type. The data Type must exactly match the argument for which data is being supplied.
  • 48. Automatically Supplied Datapoints It is normally not necessary to specify datapoints for boolean or enum arguments. Beginning with version 2.5.4, NUnit automatically supplies values of true and false for boolean arguments and will supply all defined values of any enumeration. If for some reason you don't wish to use all possible values, you can override this behavior by supplying your own datapoints. If you supply any datapoints for an argument, automatic datapoint 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 System Imports Nunit.Framework Namespace Nunit.Tests <TestFixture(), Description("Fixture description here")>_ Public Class SomeTests <Test(), Description("Test description here")>_ Public Sub OneTest() ' ... End Sub End Class End Namespace [assembly:Description("Assembly description here")] #using <Nunit.Framework.dll> using namespace System; using namespace NUnit::Framework;
  • 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 Description attribute 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 a number of positional and named parameters, which we will discuss in separate sections according to the purpose they serve. Specifying the Expected Exception Type The original attribute, introduced with NUnit 2.0 took a single argument giving the exact type of the expected exception. For example... [ExpectedException( typeof( ArgumentException ) )] public void TestMethod() { ...
  • 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.Argument exception is thrown. Specifying the Expected Message NUnit 2.1 introduced a constructor with a second argument, specifying the exact text of the message property of the exception. After NUnit 2.2.4, the same extension was made to the constructor taking a string argument. With NUnit 2.4, these arguments are marked obsolete, and a named parameter is provided instead... // Obsolete form: [ExpectedException( typeof( ArgumentException ), "expected message" )] [ExpectedException( "System.ArgumentException", "expected message" )] // Prefered form: [ExpectedException( typeof( ArgumentException ), ExpectedMessage="expected message" )] [ExpectedException( "System.ArgumentException", ExpectedMessage="expected message" )] With NUnit 2.4, it is possible to specify additional tests on the exception message, beyond a simple exact match. This is done using the MatchType named parameter, whose argument is an enumeration, 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 message containing "unspecified" is received. [ExpectedException( typeof( ArgumentException), ExpectedMessage="unspecified", MatchType=MessageMatch.Contains )] public void TestMethod() {
  • 51. ... If MatchType is not specified, an exact match is used as before. Specifying a Custom Error Message With NUnit 2.4, it is possible to specify a custom message to be displayed if the ExpectedException attribute is not satisfied. This is done through the UserMessage named parameter... [ExpectedException( typeof( ArgumentException ), UserMessage="Custom message" )] public void TestMethod() { ... Handling the Exception in Code If 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 is particularly useful when multiple exceptions need to be processed in the same way. An common exception handler may be designated by implementing the IExpectExceptionInterface, 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 may be 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. 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 normal exception handler applies to any other methods that specify an ExpectedException. However it is specified, the handler method should examine the exception and Assert on whatever properties are relevant. Any resulting failure message will then be consistent in format with 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 System Imports Nunit.Framework Namespace 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 Class End Namespace #using <Nunit.Framework.dll> using namespace System; using namespace NUnit::Framework; namespace NUnitTests {
  • 53. [TestFixture] public __gc class SuccessTests { [Test] [ExpectedException(__typeof(InvalidOperationException))] void ExpectAnExceptionByType(); [Test] [ExpectedException(S"SystemInvalidOperationException")] void ExpectAnExceptionByName(); }; } #include "cppsample.h" namespace NUnitTests { // ... } ExplicitAttribute (NUnit 2.2) The Explicit attribute causes a test or test fixture to be ignored unless it is explicitly selected for running. The test or fixture will be run if it is selected in the gui, if its name is specified on the console runner command line as the fixture to run or if it is included by use of a Category filter. An optional string argument may be used to give the reason for marking the test Explicit. If a test or fixture with the Explicit attribute is encountered in the course of running tests, it is skipped unless it has been specifically selected by one of the above means. The test does not affect the outcome of the run at all: it is not considered as ignored and is not even counted in the total number of tests. In the gui, the tree node for the test remains gray and the status bar color is not affected. Note: In versions of NUnit prior to 2.4, these tests were shown as ignored. Test Fixture Syntax namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture, Explicit] public class ExplicitTests { // ... } } Imports System Imports Nunit.Framework Namespace Nunit.Tests
  • 54. <TestFixture(), Explicit()> Public Class ExplicitTests ' ... End Class End Namespace #using <Nunit.Framework.dll> using namespace System; using namespace NUnit::Framework; namespace NUnitTests { [TestFixture] [Explicit] public __gc class ExplicitTests { // ... }; } #include "cppsample.h" namespace NUnitTests { // ... } package NUnit.Tests; import System.*; import NUnit.Framework.TestFixture; /** @attribute NUnit.Framework.TestFixture() */ /** @attribute NUnit.Framework.Explicit() */ public class ExplicitTests { // ... } Test Syntax namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test, Explicit] public void ExplicitTest() { /* ... */ } } Imports System Imports Nunit.Framework
  • 55. Namespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Explicit()> Public Sub ExplicitTest() ' ... End Sub End Class End Namespace #using <Nunit.Framework.dll> using namespace System; using namespace NUnit::Framework; namespace NUnitTests { [TestFixture] public __gc class SuccessTests { [Test][Explicit] void ExplicitTest(); }; } #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.Explicit() */ public void ExplicitTest() { /* ... */ } } IgnoreAttribute (NUnit 2.0) The ignore attribute is an attribute to not run a test or test fixture for a period of time. The person marks either a Test or a TestFixture with the Ignore Attribute. The running program sees the attribute and does not run the test or tests. The progress bar will turn yellow if a test is not run and the test will be mentioned in the reports that it was not run. This feature should be used to temporarily not run a test or fixture. This is a better mechanism than commenting out the test or renaming methods, since the tests will be compiled with the rest of the code and there is an indication at run time that a test is not being run. This insures that tests will not be forgotten.