• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
What Do You Mean By NUnit
 

What Do You Mean By NUnit

on

  • 965 views

 

Statistics

Views

Total Views
965
Views on SlideShare
965
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    What Do You Mean By NUnit What Do You Mean By NUnit Document Transcript

    • What Is NUnit? NUnit is a unit-testing framework for all .Net languages. Initially ported fromJUnit, the current production release, version 2.5, is the sixth major release of this xUnit basedunit testing tool for Microsoft .NET. It is written entirely in C# and has been completelyredesigned to take advantage of many .NET language features, for example custom attributes andother reflection related capabilities. NUnit brings xUnit to all .NET languages.Definition • NUnit is an automated unit-testing framework for all .Net languages.• Initially ported from JUnit, which is a unit testing framework for Java applications.• It is written entirely in C# and has been completely redesigned to take advantage of many .NETlanguage features.• NUnit brings xUnit to all test are written in .NET supported language e.g. C#, VC, VB.NET, J#etc.• NUnit is an open source free to use with your .NET projects.• NUnit provides a class library which includes some classes, features and methods to help youwrite test scripts.• NUnit provides user interface application to execute the test scripts and displays result• NUnit does not create any test scripts by itself. We have to write test scripts and use NUnittools and classes to make the unit testing easier and display the result as a success or failure. Features of NUnit • Assertions• Attributes 1. Assertions Definition Assertions are central to unit testing in any of the xUnit frameworks,and NUnit is no exception. NUnit provides a rich set of assertions as static methods of the Assertclass.The most commonly used assertions.• Equality Asserts ,• Identity Asserts • Comparison Asserts • Type Asserts• Condition tests,• Utility methods,• StringAssert,• CollectionAssert,• FileAssert• Equal Constraint (Available NUnit 2.4)• Same As Constraint (Available NUnit 2.4)• Condition Constraints (Available NUnit 2.4) • Comparison Constraints (Available NUnit 2.4)• Type Constraints (Available NUnit 2.4)• String Constraints (Available NUnit 2.4)• Collection Constraints (Available NUnit 2.4)• Compound Constraints (Available NUnit 2.4)• Custom Constraints (Available NUnit 2.4) 2. Attributes • Category • Description • Expected Exception • Explicit • Ignore • Platform • Property• SetUp • SetUpFixture • Suite • TearDown • Test • TestFixture • TestFixtureSetUp• TestFixtureTearDownAdd References in Project Browse references from C:Program FilesNUnit2.5.2binnet-2.0framework i.e. nunit.framework.dllAssertions
    • Assertions are central to unit testing in any of the xUnit frameworks, and NUnit is no exception.NUnit provides a rich set of assertions as static methods of the Assert class.If an assertion fails, the method call does not return and an error is reported. If a test containsmultiple assertions, any that follow the one that failed will not be executed. For this reason, itsusually best to try for one assertion per test.Each method may be called without a message, with a simple text message or with a messageand arguments. In the last case the message is formatted using the provided text and arguments.Two ModelsBefore NUnit 2.4, a separate method of the Assert class was used for each different assertion.We call this the "Classic Model." It continues to be supported in NUnit, since many peopleprefer it.Beginning with NUnit 2.4, a new "Constraint-based" model was introduced. This approach usesa single method of the Assert class for all assertions, passing a Constraint object that specifiesthe test to be performed.This constraint-based model is now used internally by NUnit for all assertions. The methods ofthe classic approach have been re-implemented on top of this new model.Equality AssertsThese methods test whether the two arguments are equal. Overloaded methods are provided forcommon value types so that languages that dont automatically box values can use them directly.Comparing Numerics of Different TypesThe method overloads that compare two objects make special provision so that numeric values ofdifferent types compare as expected. This assert succeeds: Assert.AreEqual( 5, 5.0 );Comparing Floating Point ValuesValues of type float and double are normally compared using an additional argument thatindicates a tolerance within which they will be considered as equal. Beginning with NUnit 2.4.4,the value of GlobalSettings.DefaultFloatingPointTolerance is used if a third argument is notprovided. In earlier versions, or if the default has not been set, values are tested for exactequality.Special values are handled so that the following Asserts succeed: Assert.AreEqual ( double.PositiveInfinity, double.PositiveInfinity );
    • Assert.AreEqual( double.NegativeInfinity, double.NegativeInfinity ); Assert.AreEqual( double.NaN, double.NaN );Note: The last example above represents a change with NUnit 2.2.3. In earlier releases, the test wouldfail. We have made this change because the new behavior seems to be more useful in tests. To avoidconfusion, we suggest using the new Assert.IsNaN method where appropriate.Comparing Arrays and CollectionsSince version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginningwith version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections maybe compared. Two arrays or collections will be treated as equal by Assert.AreEqual if they havethe same dimensions and if each of the corresponding elements is equal.Identity AssertsAssert.AreSame and Assert.AreNotSame test whether the same objects are referenced by thetwo arguments.Assert.AreSame( object expected, object actual );Assert.AreSame( object expected, object actual, string message );Assert.AreSame( object expected, object actual, string message, params object[] parms );Assert.AreNotSame( object expected, object actual );Assert.AreNotSame( object expected, object actual, string message );Assert.AreNotSame( object expected, object actual, string message, params object[] parms );Assert.Contains is used to test whether an object is contained in an array or list.Assert.Contains( object anObject, IList collection );Assert.Contains( object anObject, IList collection, string message );Assert.Contains( object anObject, IList collection, string message, params object[] parms );Condition AssertsMethods that test a specific condition are named for the condition they test and take the valuetested as their first argument and, optionally a message as the second. The following methods areprovided:Assert.IsTrue( bool condition );Assert.IsTrue( bool condition, string message );Assert.IsTrue( bool condition, string message, object[] parms );Assert.True( bool condition );Assert.True( bool condition, string message );Assert.True( bool condition, string message, object[] parms );
    • Assert.IsFalse( bool condition);Assert.IsFalse( bool condition, string message );Assert.IsFalse( bool condition, string message, object[] parms );Assert.False( bool condition);Assert.False( bool condition, string message );Assert.False( bool condition, string message, object[] parms );Assert.IsNull( object anObject );Assert.IsNull( object anObject, string message );Assert.IsNull( object anObject, string message, object[] parms );Assert.Null( object anObject );Assert.Null( object anObject, string message );Assert.Null( object anObject, string message, object[] parms );Assert.IsNotNull( object anObject );Assert.IsNotNull( object anObject, string message );Assert.IsNotNull( object anObject, string message, object[] parms );Assert.NotNull( object anObject );Assert.NotNull( object anObject, string message );Assert.NotNull( object anObject, string message, object[] parms );Assert.IsNaN( double aDouble );Assert.IsNaN( double aDouble, string message );Assert.IsNaN( double aDouble, string message, object[] parms );Assert.IsEmpty( string aString );Assert.IsEmpty( string aString, string message );Assert.IsEmpty( string aString, string message, params object[] args );Assert.IsNotEmpty( string aString );Assert.IsNotEmpty( string aString, string message );Assert.IsNotEmpty( string aString, string message, params object[] args );Assert.IsEmpty( ICollection collection );Assert.IsEmpty( ICollection collection, string message );Assert.IsEmpty( ICollection collection, string message, params object[] args );Assert.IsNotEmpty( ICollection collection );Assert.IsNotEmpty( ICollection collection, string message );Assert.IsNotEmpty( ICollection collection, string message, params object[] args );Two forms are provided for the True, False, Null and NotNull conditions. The "Is" forms arecompatible with earlier versions of the NUnit framework, while those without "Is" are providedfor compatibility with NUnitLite.Assert.IsEmpty and Assert.IsNotEmpty may be used to test either a string or a collection.
    • Comparisons (NUnit 2.2.4)The following methods test whether one object is greater than than another. Contrary to thenormal order of Asserts, these methods are designed to be read in the "natural" English-languageor mathematical order. Thus Assert.Greater( x, y ) asserts that x is greater than y ( x > y ).Assert.Greater( int arg1, int arg2 );Assert.Greater( int arg1, int arg2, string message );Assert.Greater( int arg1, int arg2, string message, object[] parms );Assert.Greater( uint arg1, uint arg2 );Assert.Greater( uint arg1, uint arg2, string message );Assert.Greater( uint arg1, uint arg2, string message, object[] parms );Assert.Greater( long arg1, long arg2 );Assert.Greater( long arg1, long arg2, string message );Assert.Greater( long arg1, long arg2, string message, object[] parms );Assert.Greater( ulong arg1, ulong arg2 );Assert.Greater( ulong arg1, ulong arg2, string message );Assert.Greater( ulong arg1, ulong arg2, string message, object[] parms );Assert.Greater( decimal arg1, decimal arg2 );Assert.Greater( decimal arg1, decimal arg2, string message );Assert.Greater( decimal arg1, decimal arg2, string message, object[] parms );Assert.Greater( double arg1, double arg2 );Assert.Greater( double arg1, double arg2, string message );Assert.Greater( double arg1, double arg2, string message, object[] parms );Assert.Greater( double arg1, double arg2 );Assert.Greater( double arg1, double arg2, string message );Assert.Greater( double arg1, double arg2, string message, object[] parms );Assert.Greater( float arg1, float arg2 );Assert.Greater( float arg1, float arg2, string message );Assert.Greater( float arg1, float arg2, string message, object[] parms );Assert.Greater( IComparable arg1, IComparable arg2 );Assert.Greater( IComparable arg1, IComparable arg2, string message );Assert.Greater( IComparable arg1, IComparable arg2, string message, object[] parms );The following methods test whether one object is greater than or equal to another. Contrary tothe normal order of Asserts, these methods are designed to be read in the "natural" English-
    • language or mathematical order. Thus Assert.GreaterOrEqual( x, y ) asserts that x is greaterthan or equal to y ( x >= y ).Assert.GreaterOrEqual( int arg1, int arg2 );Assert.GreaterOrEqual( int arg1, int arg2, string message );Assert.GreaterOrEqual( int arg1, int arg2, string message, object[] parms );Assert.GreaterOrEqual( uint arg1, uint arg2 );Assert.GreaterOrEqual( uint arg1, uint arg2, string message );Assert.GreaterOrEqual( uint arg1, uint arg2, string message, object[] parms );Assert.GreaterOrEqual( long arg1, long arg2 );Assert.GreaterOrEqual( long arg1, long arg2, string message );Assert.GreaterOrEqual( long arg1, long arg2, string message, object[] parms );Assert.GreaterOrEqual( ulong arg1, ulong arg2 );Assert.GreaterOrEqual( ulong arg1, ulong arg2, string message );Assert.GreaterOrEqual( ulong arg1, ulong arg2, string message, object[] parms );Assert.GreaterOrEqual( decimal arg1, decimal arg2 );Assert.GreaterOrEqual( decimal arg1, decimal arg2, string message );Assert.GreaterOrEqual( decimal arg1, decimal arg2, string message, object[] parms );Assert.GreaterOrEqual( double arg1, double arg2 );Assert.GreaterOrEqual( double arg1, double arg2, string message );Assert.GreaterOrEqual( double arg1, double arg2, string message, object[] parms );Assert.GreaterOrEqual( double arg1, double arg2 );Assert.GreaterOrEqual( double arg1, double arg2, string message );Assert.GreaterOrEqual( double arg1, double arg2, string message, object[] parms );Assert.GreaterOrEqual( float arg1, float arg2 );Assert.GreaterOrEqual( float arg1, float arg2, string message );Assert.GreaterOrEqual( float arg1, float arg2, string message, object[] parms );Assert.GreaterOrEqual( IComparable arg1, IComparable arg2 );Assert.GreaterOrEqual( IComparable arg1, IComparable arg2, string message );Assert.GreaterOrEqual( IComparable arg1, IComparable arg2, string message, object[] parms );The following methods test whether one object is less than than another. Contrary to the normalorder of Asserts, these methods are designed to be read in the "natural" English-language ormathematical order. Thus Assert.Less( x, y ) asserts that x is less than y ( x < y ).Assert.Less( int arg1, int arg2 );Assert.Less( int arg1, int arg2, string message );Assert.Less( int arg1, int arg2, string message,
    • object[] parms );Assert.Less( uint arg1, uint arg2 );Assert.Less( uint arg1, uint arg2, string message );Assert.Less( uint arg1, uint arg2, string message, object[] parms );Assert.Less( long arg1, long arg2 );Assert.Less( long arg1, long arg2, string message );Assert.Less( long arg1, long arg2, string message, object[] parms );Assert.Less( ulong arg1, ulong arg2 );Assert.Less( ulong arg1, ulong arg2, string message );Assert.Less( ulong arg1, ulong arg2, string message, object[] parms );Assert.Less( decimal arg1, decimal arg2 );Assert.Less( decimal arg1, decimal arg2, string message );Assert.Less( decimal arg1, decimal arg2, string message, object[] parms );Assert.Less( double arg1, double arg2 );Assert.Less( double arg1, double arg2, string message );Assert.Less( double arg1, double arg2, string message, object[] parms );Assert.Less( float arg1, float arg2 );Assert.Less( float arg1, float arg2, string message );Assert.Less( float arg1, float arg2, string message, object[] parms );Assert.Less( IComparable arg1, IComparable arg2 );Assert.Less( IComparable arg1, IComparable arg2, string message );Assert.Less( IComparable arg1, IComparable arg2, string message, object[] parms );The following methods test whether one object is less than or equal to another. Contrary to thenormal order of Asserts, these methods are designed to be read in the "natural" English-languageor mathematical order. Thus Assert.LessOrEqual( x, y ) asserts that x is less than or equal to y (x <= y ).Assert.LessOrEqual( int arg1, int arg2 );Assert.LessOrEqual( int arg1, int arg2, string message );Assert.LessOrEqual( int arg1, int arg2, string message, object[] parms );Assert.LessOrEqual( uint arg1, uint arg2 );Assert.LessOrEqual( uint arg1, uint arg2, string message );Assert.LessOrEqual( uint arg1, uint arg2, string message, object[] parms );Assert.LessOrEqual( long arg1, long arg2 );Assert.LessOrEqual( long arg1, long arg2, string message );Assert.LessOrEqual( long arg1, long arg2, string message,
    • 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, itattempts to invoke a code snippet, represented as a delegate, in order to verify that it throws aparticular exception.Its also in a class by itself in that it returns an Exception, rather than void, if the Assert issuccessful. See the example below for a few ways to use this.Assert.Throws may be used with a constraint argument, which is applied to the actual exceptionthrown, or with the Type of exception expected. The Type format is available in both both a non-generic and (in the .NET 2.0 version) generic form.Assert.DoesNotThrow simply verifies that the delegate does not throw an exception.Assert.Catch is similar to Assert.Throws but will pass for an exception that is derived from theone specified.Exception Assert.Throws( Type expectedExceptionType, TestDelegate code );Exception Assert.Throws( Type expectedExceptionType, TestDelegate code, string message );Exception Assert.Throws( Type expectedExceptionType, TestDelegate code, string message, params object[] parms);Exception Assert.Throws( IResolveConstraint constraint, TestDelegate code );Exception Assert.Throws( IResolveConstraint constraint, TestDelegate code, string message );Exception Assert.Throws( IResolveConstraint constraint, TestDelegate code,
    • string message, params object[] parms);T Assert.Throws<T>( TestDelegate code );T Assert.Throws<T>( TestDelegate code, string message );T Assert.Throws<T>( TestDelegate code, string message, params object[] parms);void Assert.DoesNotThrow( TestDelegate code );void Assert.DoesNotThrow( TestDelegate code, string message );void Assert.DoesNotThrow( TestDelegate code, string message, params object[] parms);Exception Assert.Catch( TestDelegate code );Exception Assert.Catch( TestDelegate code, string message );Exception Assert.Catch( TestDelegate code, string message, params object[] parms);Exception Assert.Catch( Type expectedExceptionType, TestDelegate code );Exception Assert.Catch( Type expectedExceptionType, TestDelegate code, string message );Exception Assert.Catch( Type expectedExceptionType, TestDelegate code, string message, params object[] parms);T Assert.Catch<T>( TestDelegate code );T Assert.Catch<T>( TestDelegate code, string message );T Assert.Catch<T>( TestDelegate code, string message, params object[] parms);In the above code TestDelegate is a delegate of the form void TestDelegate(), which is used toexecute the code in question. Under .NET 2.0, this may be an anonymous delegate. If compilingunder C# 3.0, it may be a lambda expression.The following example shows different ways of writing the same test.[TestFixture]public class AssertThrowsTests{ [Test] public void Tests() { // .NET 1.x Assert.Throws( typeof(ArgumentException), new TestDelegate(MethodThatThrows) ); // .NET 2.0 Assert.Throws<ArgumentException>( MethodThatThrows() ); Assert.Throws<ArgumentException>( delegate { throw new ArgumentException(); } ); // Using C# 3.0 Assert.Throws<ArgumentException>( () => throw new ArgumentException(); } ); }
    • void MethodThatThrows() { throw new ArgumentException(); }This example shows use of the return value to perform additional verification of the exception.[TestFixture]public class UsingReturnValue{ [Test] public void TestException() { MyException ex = Assert.Throws<MyException>( delegate { throw new MyException( "message", 42 ); } ); Assert.That( ex.Message, Is.EqualTo( "message" ) ); Assert.That( ex.MyParam, Is.EqualTo( 42 ) ); }This example does the same thing using the overload that includes a constraint.[TestFixture]public class UsingConstraint{ [Test] public void TestException() { Assert.Throws( Is.Typeof<MyException>() .And.Message.EqualTo( "message" ) .And.Property( "MyParam" ).EqualTo( 42 ), delegate { throw new MyException( "message", 42 ); } ); }Use the form that matches your style of coding.Exact Versus Derived TypesWhen used with a Type argument, Assert.Throws requires that exact type to be thrown. If youwant to test for any derived Type, use one of the forms that allows specifying a constraint.Alternatively, you may use Assert.Catch, which differs from Assert.Throws in allowingderived types. See the following code for examples:// Require an ApplicationException - derived types fail!Assert.Throws( typeof(ApplicationException), code );Assert.Throws<ApplicationException>()( code );// Allow both ApplicationException and any derived typeAssert.Throws( Is.InstanceOf( typeof(ApplicationException), code );Assert.Throws( Is.InstanceOf<ApplicationException>(), code );// Allow both ApplicationException and any derived typeAssert.Catch<ApplicationException>( code );
    • // Allow any kind of exceptionAssert.Catch( code ); Utility Methods 1. Four utility methods, Pass(), Fail(), Ignore() and Inconclusive() are provided in order to allow more direct control of the test process: 2. Assert.Pass(); 3. Assert.Pass( string message ); 4. Assert.Pass( string message, object[] parms ); 5. 6. Assert.Fail(); 7. Assert.Fail( string message ); 8. Assert.Fail( string message, object[] parms ); 9. 10. Assert.Ignore(); 11. Assert.Ignore( string message ); 12. Assert.Ignore( string message, object[] parms ); 13. 14. Assert.Inconclusive(); 15. Assert.Inconclusive( string message ); 16. Assert.Inconclusive( string message, object[] parms ); 17. The Assert.Pass method allows you to immediately end the test, recording it as successful. Since it causes an exception to be thrown, it is more efficient to simply allow the test to return. However, Assert.Pass allows you to record a message in the test result and may also make the test easier to read in some situations. Additionally, like the other methods on this page, it can be invoked from a nested method call with the result of immediately terminating test execution. 18. The Assert.Fail method provides you with the ability to generate a failure based on tests that are not encapsulated by the other methods. It is also useful in developing your own project-specific assertions. 19. Heres an example of its use to create a private assertion that tests whether a string contains an expected value. 20. public void AssertStringContains( string expected, string actual ) 21. { 22. AssertStringContains( expected, actual, string.Empty ); 23. } 24. 25. public void AssertStringContains( string expected, string actual, 26. string message ) 27. { 28. if ( actual.IndexOf( expected ) < 0 ) 29. Assert.Fail( message ); 30. } 31. The Assert.Ignore method provides you with the ability to dynamically cause a test or suite to be ignored at runtime. It may be called in a test, setup or fixture setup method. We recommend that you use this only in isolated cases. The category facility is provided for more extensive inclusion or exclusion of tests or you may elect to simply divide tests run on different occasions into different assemblies.
    • 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 actual89. string message, params object[] args );90.91. CollectionAssert.AreEquivalent( IEnumerable expected, IEnumerable actual);92. CollectionAssert.AreEquivalent( IEnumerable expected, IEnumerable actual,93. string message );94. CollectionAssert.AreEquivalent( IEnumerable expected, IEnumerable actual95. string message, params object[] args );96.97. CollectionAssert.AreNotEqual( IEnumerable expected, IEnumerable actual );98. CollectionAssert.AreNotEqual( IEnumerable expected, IEnumerable actual,99. string message );100. CollectionAssert.AreNotEqual( IEnumerableon expected, IEnumerable actual101. string message, params object[] args );102.103. CollectionAssert.AreNotEquivalent( IEnumerable expected,104. IEnumerable actual );105. CollectionAssert.AreNotEquivalent( IEnumerable expected,106. IEnumerable actual, string message );107. CollectionAssert.AreNotEquivalent( IEnumerable expected,108. IEnumerable actual, string message, params object[] args );109.110. CollectionAssert.Contains( IEnumerable expected, object actual );111. CollectionAssert.Contains( IEnumerable expected, object actual,112. string message );113. CollectionAssert.Contains( IEnumerable expected, object actual114. string message, params object[] args );115.116. CollectionAssert.DoesNotContain( IEnumerable expected, object actual );117. CollectionAssert.DoesNotContain( IEnumerable expected, object actual,118. string message );119. CollectionAssert.DoesNotContain( IEnumerable expected, object actual
    • 120. string message, params object[] args ); 121. 122. CollectionAssert.IsSubsetOf( IEnumerable subset, IEnumerable superset ); 123. CollectionAssert.IsSubsetOf( IEnumerable subset, IEnumerable superset, 124. string message ); 125. CollectionAssert.IsSubsetOf( IEnumerable subset, IEnumerable superset, 126. string message, params object[] args ); 127. 128. CollectionAssert.IsNotSubsetOf( IEnumerable subset, IEnumerable superset); 129. CollectionAssert.IsNotSubsetOf( IEnumerable subset, IEnumerable superset, 130. string message ); 131. CollectionAssert.IsNotSubsetOf( IEnumerable subset, IEnumerable superset, 132. string message, params object[] args ); 133. 134. CollectionAssert.IsEmpty( IEnumerable collection ); 135. CollectionAssert.IsEmpty( IEnumerable collection, string message ); 136. CollectionAssert.IsEmpty( IEnumerable collection, string message, 137. params object[] args ); 138. 139. CollectionAssert.IsNotEmpty( IEnumerable collection ); 140. CollectionAssert.IsNotEmpty( IEnumerable collection, string message ); 141. CollectionAssert.IsNotEmpty( IEnumerable collection, string message, 142. params object[] args ); 143. The following methods are available beginning with NUnit 2.5 144. CollectionAssert.IsOrdered( IEnumerable collection ); 145. CollectionAssert.IsOrdered( IEnumerable collection, string message ); 146. CollectionAssert.IsOrdered( IEnumerable collection, string message, 147. params object[] args ); 148. 149. CollectionAssert.IsOrdered( IEnumerable collection, IComparer comparer ); 150. CollectionAssert.IsOrdered( IEnumerable collection, IComparer comparer, 151. string message ); 152. CollectionAssert.IsOrdered( IEnumerable collection, IComparer comparer, 153. string message, params object[] args );FileAssert (NUnit 2.4)The FileAssert class provides methods for comparing two files, which may be provided asStreams, as FileInfos or as strings giving the path to each file.FileAssert.AreEqual( Stream expected, Stream actual );FileAssert.AreEqual( Stream expected, Stream actual, string message );FileAssert.AreEqual( Stream expected, Stream actual, string message, params object[] args );
    • FileAssert.AreEqual( FileInfo expected, FileInfo actual );FileAssert.AreEqual( FileInfo expected, FileInfo actual, string message );FileAssert.AreEqual( FileInfo expected, FileInfo actual, string message, params object[] args );FileAssert.AreEqual( string expected, string actual );FileAssert.AreEqual( string expected, string actual, string message );FileAssert.AreEqual( string expected, string actual, string message, params object[] args );FileAssert.AreNotEqual( Stream expected, Stream actual );FileAssert.AreNotEqual( Stream expected, Stream actual, string message );FileAssert.AreNotEqual( Stream expected, Stream actual, string message, params object[] args );FileAssert.AreNotEqual( FileInfo expected, FileInfo actual );FileAssert.AreNotEqual( FileInfo expected, FileInfo actual, string message );FileAssert.AreNotEqual( FileInfo expected, FileInfo actual, string message, params object[] args );FileAssert.AreNotEqual( string expected, string actual );FileAssert.AreNotEqual( string expected, string actual, string message );FileAssert.AreNotEqual( string expected, string actual, string message, params object[] args );DirectoryAssert (NUnit 2.5)The DirectoryAssert class provides methods for making asserts about file system directories,which may be provided as DirectoryInfos or as strings giving the path to each directory.DirectoryAssert.AreEqual() and DirectoryAssert.AreNotEqual() compare two directories forequality. Directories are considered equal if they have the same FullName, Attributes,CreationTime and LastAccessTime.Note: Two different directories containing the same files are not considered to be equal.DirectoryAssert.AreEqual( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.AreEqual( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.AreEqual( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.AreEqual( string expected, string actual );DirectoryAssert.AreEqual( string expected, string actual, string message );DirectoryAssert.AreEqual( string expected, string actual,
    • string message, params object[] args );DirectoryAssert.AreNotEqual( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.AreNotEqual( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.AreNotEqual( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.AreNotEqual( string expected, string actual );DirectoryAssert.AreNotEqual( string expected, string actual, string message );DirectoryAssert.AreNotEqual( string expected, string actual, string message, params object[] args );DirectoryAssert.IsEmpty() and DirectoryAssert.IsNotEmpty() test whether the specifieddirectory is empty.DirectoryAssert.IsEmpty( DirectoryInfo directory );DirectoryAssert.IsEmpty( DirectoryInfo directory, string message );DirectoryAssert.IsEmpty( DirectoryInfo directory, string message, params object[] args );DirectoryAssert.IsEmpty( string directory );DirectoryAssert.IsEmpty( string directory, string message );DirectoryAssert.IsEmpty( string directory, string message, params object[] args );DirectoryAssert.IsNotEmpty( DirectoryInfo directory );DirectoryAssert.IsNotEmpty( DirectoryInfo directory, string message );DirectoryAssert.IsNotEmpty( DirectoryInfo directory, string message, params object[] args );DirectoryAssert.IsNotEmpty( string directory );DirectoryAssert.IsNotEmpty( string directory, string message );DirectoryAssert.IsNotEmpty( string directory, string message, params object[] args );DirectoryAssert.IsWithin() and DirectoryAssert.IsNotWithin() test whether the seconddirectory is a direct or indirect subdirectory of the first directory.DirectoryAssert.IsWithin( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.IsWithin( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.IsWithin( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.IsWithin( string expected, string actual );DirectoryAssert.IsWithin( string expected, string actual, string message );DirectoryAssert.IsWithin( string expected, string actual, string message, params object[] args );
    • DirectoryAssert.IsNotWithin( DirectoryInfo expected, DirectoryInfo actual );DirectoryAssert.IsNotWithin( DirectoryInfo expected, DirectoryInfo actual, string message );DirectoryAssert.IsNotWithin( DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args );DirectoryAssert.IsNotWithin( string expected, string actual );DirectoryAssert.IsNotWithin( string expected, string actual, string message );DirectoryAssert.IsNotWithin( string expected, string actual, string message, params object[] args );Constraint-Based Assert Model (NUnit 2.4)The constraint-based Assert model uses a single method of the Assert class for all assertions. Thelogic necessary to carry out each assertion is embedded in the constraint object passed as thesecond parameter to that method.Heres a very simple assert using the constraint model: Assert.That( myString, Is.EqualTo("Hello") );The second argument in this assertion uses one of NUnits syntax helpers to create anEqualConstraint. The same assertion could also be made in this form: Assert.That( myString, new EqualConstraint("Hello") );Using this model, all assertions are made using one of the forms of the Assert.That() method,which has a number of overloads...Assert.That( object actual, IResolveConstraint constraint )Assert.That( object actual, IResolveConstraint constraint, string message )Assert.That( object actual, IResolveConstraint constraint, string message, object[] parms )Assert.That( ActualValueDelegate del, IResolveConstraint constraint )Assert.That( ActualValueDelegate del, IResolveConstraint constraint, string message )Assert.That( ActualValueDelegate del, IResolveConstraint constraint, string message, object[] parms )Assert.That( ref T actual, IResolveConstraint constraint )Assert.That( ref T actual, IResolveConstraint constraint, string message )Assert.That( ref T actual, IResolveConstraint constraint, string message, object[] parms )Assert.That( bool condition );Assert.That( bool condition, string message );
    • Assert.That( bool condition, string message, object[] parms );Assert.That( TestDelegate del, IResolveConstraint constraint );If you derive your test fixture class from AssertionHelper, the Expect() method may be used inplace of Assert.That()...Expect( object actual, IResolveConstraint constraint )Expect( object actual, IResolveConstraint constraint, string message )Expect( object actual, IResolveConstraint constraint, string message, object[] parms )Expect( ActualValueDelegate del, IResolveConstraint constraint )Expect( ActualValueDelegate del, IResolveConstraint constraint, string message )Expect( ActualValueDelegate del, IResolveConstraint constraint, string message, object[] parms )Expect( ref T actual, IResolveConstraint constraint )Expect( ref T actual, IResolveConstraint constraint, string message )Expect( ref T actual, IResolveConstraint constraint, string message, object[] parms )Expect( bool condition );Expect( bool condition, string message );Expect( bool condition, string message, object[] parms );Expect( TestDelegate del, IResolveConstraint constraint );The overloads that take a bool work exactly like Assert.IsTrue.For overloads taking a constraint, the argument must be a object implementing the IConstraintinterface, which supports performing a test on an actual value and generating appropriatemessages. This interface is described in more detail under Custom Constraints.NUnit provides a number of constraint classes similar to the EqualConstraint used in theexample above. Generally, these classes may be used directly or through a syntax helper. Testfixture classes inheriting from AssertionHelper are able to use shorter forms. The valid formsare described on the pages related to each constraint. Note that the menu items listed to the rightgenerally reflect the names of the syntax helpers.Equal Constraint (NUnit 2.4 / 2.5)An EqualConstraint is used to test whether an actual value is equal to the expected valuesupplied in its constructor, optionally within a specified tolerance.ConstructorEqualConstraint(object expected )
    • SyntaxIs.EqualTo( object expected )Modifiers...IgnoreCase...AsCollection...NoClip...Within(object tolerance) .Ulps .Percent .Days .Hours .Minutes .Seconds .Milliseconds .Ticks...Using(IEqualityComparer comparer)...Using(IEqualityComparer<T> comparer)...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Comparing NumericsNumerics are compared based on their values. Different types may be compared successfully iftheir values are equal.Using the Within modifier, numerics may be tested for equality within a fixed or percenttolerance.Assert.That(2 + 2, Is.EqualTo(4.0));Assert.That(2 + 2 == 4);Assert.That(2 + 2, Is.Not.EqualTo(5));Assert.That(2 + 2 != 5);Assert.That( 5.0, Is.EqualTo( 5 );Assert.That( 5.5, Is.EqualTo( 5 ).Within(0.075);Assert.That( 5.5, Is.EqualTo( 5 ).Within(1.5).Percent;Comparing Floating Point ValuesValues of type float and double are normally compared using a tolerance specified by the Withinmodifier. The special values PositiveInfinity, NegativeInfinity and NaN compare as equal tothemselves.With version 2.5, floating-point values may be compared using a tolerance in "Units in the LastPlace" or ULPs. For certain types of numerical work, this is safer than a fixed tolerance becauseit automatically compensates for the added inaccuracy of larger numbers.Assert.That( 2.1 + 1.2, Is.EqualTo( 3.3 ).Within( .0005 );Assert.That( double.PositiveInfinity, Is.EqualTo( double.PositiveInfinity ));
    • Assert.That( double.NegativeInfinity, Is.EqualTo( double.NegativeInfinity ));Assert.That( double.NaN, Is.EqualTo( double.NaN ) );Assert.That( 20000000000000004.0,Is.EqualTo(20000000000000000.0).Within(1).Ulps);Comparing StringsString comparisons normally respect case. The IgnoreCase modifier causes the comparison tobe case-insensitive. It may also be used when comparing arrays or collections of strings.Assert.That( "Hello!", Is.Not.EqualTo( "HELLO!" ) );Assert.That( "Hello!", Is.EqualTo( "HELLO!" ).IgnoreCase );string[] expected = new string[] { "Hello", World" };string[] actual = new string[] { "HELLO", "world" };Assert.That( actual, Is.EqualTo( expected ).IgnoreCase;Comparing DateTimes and TimeSpansDateTimes and TimeSpans may be compared either with or without a tolerance. A tolerance isspecified using Within with either a TimeSpan as an argument or with a numeric valuefollowed by a one of the time conversion modifiers: Days, Hours, Minutes, Seconds,Milliseconds or Ticks.DateTime now = DateTime.Now;DateTime later = now + TimeSpan.FromHours(1.0);Assert.That( now, Is.EqualTo(now) );Assert.That( later. Is.EqualTo(now).Within(TimeSpan.FromHours(3.0);Assert.That( later, Is.EqualTo(now).Within(3).Hours;Comparing Arrays and CollectionsSince version 2.2, NUnit has been able to compare two single-dimensioned arrays. Beginningwith version 2.4, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections maybe compared. With version 2.5, any IEnumerable is supported. Two arrays, collections orIEnumerables are considered equal if they have the the same dimensions and if each of thecorresponding elements is equal.If you want to treat two arrays of different shapes as simple collections for purposes ofcomparison, use the AsCollection modifier, which causes the comparison to be made element byelement, without regard for the rank or dimensions of the array. Note that jagged arrays (arraysof arrays) do not have a single underlying collection. The modifier would be applied to eacharray separately, which has no effect in most cases.int[] i3 = new int[] { 1, 2, 3 };double[] d3 = new double[] { 1.0, 2.0, 3.0 };int[] iunequal = new int[] { 1, 3, 2 };Assert.That(i3, Is.EqualTo(d3));Assert.That(i3, Is.Not.EqualTo(iunequal));
    • int array2x2 = new int[,] { { 1, 2 } { 3, 4 } };int array4 = new int[] { 1, 2, 3, 4 };Assert.That( array2x2, Is.Not.EqualTo( array4 ) );Assert.That( array2x2, Is.EqualTo( array4 ).AsCollection );Comparing DictionariesDictionaries implement ICollection, and NUnit has treated them as collections since version 2.4.However, this did not give useful results, since the dictionary entries had to be in the same orderfor the comparison to succeed and the underlying implementation had to be the same.Beginning with NUnit 2.5.6, NUnit has specific code for comparing dictionaries. Twodictionaries are considered equal if 1. The list of keys is the same - without regard to ordering. 2. The values associated with each key are equal.You can use this capability to compare any two objects implementing IDictionary. Generic andnon-generic dictionaries (Hashtables) may be successfully compared.User-Specified ComparersIf the default NUnit or .NET behavior for testing equality doesnt meet your needs, you cansupply a comparer of your own through the Using modifier. When used with EqualConstraint,you may supply an IEqualityComparer, IEqualityComparer<T>, IComparer,IComparer<T>; or Comparison<T> as the argument to Using.Assert.That( myObj1, Is.EqualTo( myObj2 ).Using( myComparer ) );Notes 1. When checking the equality of user-defined classes, NUnit makes use of the Equals override on the expected object. If you neglect to override Equals, you can expect failures non-identical objects. In particular, overriding operator== without overriding Equals has no effect. 2. The Within modifier was originally designed for use with floating point values only. Beginning with NUnit 2.4, comparisons of DateTime values may use a TimeSpan as a tolerance. Beginning with NUnit 2.4.2, non-float numeric comparisons may also specify a tolerance. 3. Beginning with NUnit 2.4.4, float and double comparisons for which no tolerance is specified use a default, use the value of GlobalSettings.DefaultFloatingPointTolerance. If this is not set, a tolerance of 0.0d is used. 4. Prior to NUnit 2.2.3, comparison of two NaN values would always fail, as specified by IEEE floating point standards. The new behavior, was introduced after some discussion becuase it seems more useful in tests. To avoid confusion, consider using Is.NaN where appropriate.
    • 5. When an equality test between two strings fails, the relevant portion of of both strings is displayed in the error message, clipping the strings to fit the length of the line as needed. Beginning with 2.4.4, this behavior may be modified by use of the NoClip modifier on the constraint. In addition, the maximum line length may be modified for all tests by setting the value of TextMessageWriter.MaximumLineLength in the appropriate level of setup. 6. When used with arrays, collections or dictionaries, EqualConstraint operates recursively. Any modifiers are saved and used as they apply to individual items. 7. A user-specified comparer will not be called by EqualConstraint if either or both arguments are null. If both are null, the Constraint succeeds. If only one is null, it fails. 8. NUnit has special semantics for comparing Streams and DirectoryInfos. For a Stream, the contents are compared. For a DirectoryInfo, the first-level directory contents are compared.Same As Constraint (NUnit 2.4)A SameAsConstraint is used to test whether the object passed as an actual value has the sameidentity as the object supplied in its constructor.ConstructorSameAsConstraint( object expected )SyntaxIs.SameAs( object expected )Examples of UseException ex1 = new Exception();Exception ex2 = ex1;Assert.That( ex2, Is.SameAs( ex1 ) );Exception ex3 = new Exception();Assert.That( ex3, Is.Not.SameAs( ex1 ) );Condition Constraints (NUnit 2.4)ConditionConstraints test a specific condition and are named for the condition they test. Theyverify that the actual value satisfies the condition. The following condition helpers are provided.NullConstraintActionTests that a value is Null.ConstructorNullConstraint()
    • SyntaxIs.NullExamples of UseAssert.That( anObject, Is.Null );Assert.That( anObject, Is.Not.Null );TrueConstraintActionTests that a value is true.ConstructorTrueConstraint()SyntaxIs.TrueExample of UseAssert.That( condition, Is.True );FalseConstraintActionTests that a value is false.ConstructorFalseConstraint()SyntaxIs.FalseExample of UseAssert.That( condition, Is.False );NaNConstraintActionTests that a value is floating-point NaN.ConstructorNaNConstraint()SyntaxIs.NaNExamples of UseAssert.That( aDouble, Is.NaN );
    • Assert.That( aDouble, Is.Not.NaN );EmptyConstraintActionTests that an object is an empty string, directory or collection.ConstructorEmptyConstraint()SyntaxIs.EmptyExamples of UseAssert.That( aString, Is.Empty );Assert.Thst( dirInfo, Is.Empty );Assert.That( collection, Is.Empty );Notes 1. EmptyConstraint creates and uses either an EmptyStringConstraint, EmptyDirectoryConstraint or EmptyCollectionConstraint depending on the argument tested. 2. A DirectoryInfo argument is required in order to test for an empty directory. To test whether a string represents a directory path, you must first construct a DirectoryInfo.UniqueItemsConstraintActionTests that an array, collection or other IEnumerable is composed of unique items with noduplicates.ConstructorUniqueItemsConstraint()SyntaxIs.UniqueExample of UseAssert.That( collection, Is.Unique );Comparison Constraints (NUnit 2.4 / 2.5)Comparison constraints are able to test whether one value is greater or less than another.Comparison constraints work on numeric values, as well as other objects that implement theIComparable interface or - beginning with NUnit 2.5 - IComparable<T>.
    • Beginning with NUnit 2.5, you may supply your own comparison algorithm through the Usingmodifier.GreaterThanConstraintActionTests that one value is greater than another.ConstructorGreaterThanConstraint(object expected)SyntaxIs.GreaterThan(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(7, Is.GreaterThan(3));Assert.That(myOwnObject, Is.GreaterThan(theExpected).Using(myComparer));GreaterThanOrEqualConstraintActionTests that one value is greater than or equal to another.ConstructorGreaterThanOrEqualConstraint(object expected)SyntaxIs.GreaterThanOrEqualTo(object expected)Is.AtLeast(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(7, Is.GreaterThanOrEqualTo(3));Assert.That(7, Is.AtLeast(3));Assert.That(7, Is.GreaterThanOrEqualTo(7));Assert.That(7, Is.AtLeast(7));Assert.That(myOwnObject, Is.GreaterThanOrEqualTo(theExpected).Using(myComparer));
    • LessThanConstraintActionTests that one value is less than another.ConstructorLessThanConstraint(object expected)SyntaxIs.LessThan(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(3, Is.LessThan(7));Assert.That(myOwnObject, Is.LessThan(theExpected).Using(myComparer));LessThanOrEqualConstraintActionTests that one value is less than or equal to another.ConstructorLessThanOrEqualConstraint(object expected)SyntaxIs.LessThanOrEqualTo(object expected)Is.AtMost(object expected)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of UseAssert.That(3, Is.LessThanOrEqualTo(7));Assert.That(3, Is.AtMost(7));Assert.That(3, Is.LessThanOrEqualTo(3));Assert.That(3, Is.AtMost(3));Assert.That(myOwnObject, Is.LessThanOrEqualTo(theExpected).Using(myComparer));
    • RangeConstraintActionConstructorRangeConstraint(IComparable from, IComparable to)SyntaxIs.InRange(IComparable from, IComparable to)Modifiers...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of Useint[] iarray = new int[] { 1, 2, 3 }Assert.That( 42, Is.InRange(1, 100) );Assert.That( iarray, Is.All.InRange(1, 3) );Assert.That(myOwnObject, Is.InRange(lowExpected, highExpected).Using(myComparer));Path Constraints (NUnit 2.5)Path constraints perform tests on paths, without reference to any actual files or directories. Thisallows testing paths that are created by an application for reference or later use, without anyeffect on the environment.Path constraints are intended to work across multiple file systems, and convert paths to acanonical form before comparing them.It is usually not necessary to know the file system of the paths in order to compare them. Wherenecessary, the programmer may use the IgnoreCase and RespectCase modifiers to providebehavior other than the system default.SamePathConstraintActionTests that two paths are equivalent.ConstructorSamePathConstraint( string expectedPath )SyntaxIs.SamePath( string expectedPath )Modifiers...IgnoreCase
    • ...RespectCaseExamples of UseAssert.That( "/folder1/./junk/../folder2", Is.SamePath( "/folder1/folder2" ) );Assert.That( "/folder1/./junk/../folder2/x", Is.Not.SamePath( "/folder1/folder2" ) );Assert.That( @"C:folder1folder2", Is.SamePath( @"C:Folder1Folder2" ).IgnoreCase );Assert.That( "/folder1/folder2", Is.Not.SamePath( "/Folder1/Folder2" ).RespectCase );SamePathOrUnderConstraintActionTests that one path is equivalent another path or that it is under it.ConstructorSamePathOrUnderConstraint( string expectedPath )SyntaxIs.SamePathOrUnder( string expectedPath )Modifiers...IgnoreCase...RespectCaseExamples of UseAssert.That( "/folder1/./junk/../folder2", Is.SamePathOrUnder( "/folder1/folder2" ) );Assert.That( "/folder1/junk/../folder2/./folder3", Is.SamePathOrUnder( "/folder1/folder2" ) );Assert.That( "/folder1/junk/folder2/folder3", Is.Not.SamePathOrUnder( "/folder1/folder2" ) );Assert.That( @"C:folder1folder2folder3", Is.SamePathOrUnder( @"C:Folder1Folder2" ).IgnoreCase );Assert.That( "/folder1/folder2/folder3", Is.Not.SamePathOrUnder( "/Folder1/Folder2" ).RespectCase );Type Constraints (NUnit 2.4)Type constraints perform tests that are specific to Types. The following type constraints areprovided: Syntax Helper Constructor OperationIs.TypeOf( Type ) ExactTypeConstraint( Type ) tests that an object is an exact Type
    • InstanceOfTypeConstraint( TypeIs.InstanceOfType( Type ) tests that an object is an instance of a Type )Is.AssignableFrom( Type AssignableFromConstraint( Type tests that one type is assignable from) ) anotherExamples of UseAssert.That("Hello", Is.TypeOf(typeof(string)));Assert.That("Hello", Is.Not.TypeOf(typeof(int)));Assert.That("Hello", Is.InstanceOfType(typeof(string)));Assert.That(5, Is.Not.InstanceOfType(typeof(string)));Assert.That( "Hello", Is.AssignableFrom(typeof(string)));Assert.That( 5, Is.Not.AssignableFrom(typeof(string)));// Using inheritanceExpect( 5, Not.InstanceOfType(typeof(string)));Expect( "Hello", AssignableFrom(typeOf(string)));String Constraints (NUnit 2.4)String constraints perform tests that are specific to strings. Attempting to test a non-string valuewith a string constraint is an error and gives an exception.The Text prefix is deprecated beginning with NUnit 2.5.1 and will be removed in NUnit 3.0.SubstringConstraintActionTests for a substring.ConstructorSubstringConstraint(string expected)SyntaxIs.StringContaining(string expected)Contains.Substring(string expected)ContainsSubstring(string expected)Contains(string expected)[Obsolete] Text.Contains(string expected)[Obsolete] Text.DoesNotContain(string expected)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"
    • Assert.That( phrase, Is.StringContaining( "tests fail" ) );Assert.That( phrase, Contains.Substring( "tests fail" ) );Assert.That( phrase, Is.Not.StringContaining( "tests pass" ) );Assert.That( phrase, Is.StringContaining( "make" ).IgnoreCase );Expect (phrase, Contains.Substring( "make" ).IgnoreCase );Notes 1. ContainsSubstring and Contains may appear only in the body of a constraint expression or when the inherited syntax is used. 2. Contains is not actually a string constraint but is converted to one when a string is being tested.StartsWithConstraintActionTests for an initial string.ConstructorStartsWithConstraint(string expected)SyntaxIs.StringStarting(string expected)StartsWith(string expected)[Obsolete] Text.StartsWith(string expected)[Obsolete] Text.DoesNotStartWith(string expected)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"Assert.That( phrase, Is.StringStarting( "Make" ) );Assert.That( phrase, Is.Not.StringStarting( "Break" ) );Assert.That( phrase, Has.Length.GreaterThan(10) .And.Not.StartsWith( "Break" ) );Expect( phrase, StartsWith( "Make" ) );Notes 1. StartsWith may appear only in the body of a constraint expression or when the inherited syntax is used.EndsWithConstraintActionTests for an ending string.
    • ConstructorEndsWithConstraint(string expected)SyntaxIs.StringEnding(string expected)EndsWith(string expected)[Obsolete] Text.EndsWith(string expected)[Obsolete] Text.DoesNotEndWith(string expected)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"Assert.That( phrase, Is.StringEnding( "!" ) );Assert.That( phrase, Is.StringEnding( "PASSING!" ).IgnoreCase );Expect( phrase, EndsWith( "!" ) );Notes 1. EndsWith may appear only in the body of a constraint expression or when the inherited syntax is used.RegexConstraintActionTests that a pattern is matched.ConstructorRegexConstraint(string pattern)SyntaxIs.StringMatching(string pattern)Matches(string pattern)[Obsolete] Text.Matches(string pattern)[Obsolete] Text.DoesNotMatch(string pattern)Modifiers...IgnoreCaseExamples of Usestring phrase = "Make your tests fail before passing!"Assert.That( phrase, Is.StringMatching( "Make.*tests.*pass" ) );Assert.That( phrase, Is.Not.StringMatching( "your.*passing.*tests" ) );Assert.That( phrase, Has.Length.GreaterThan(10) .And.Not.Matches( "your.*passing.*tests" ) );Expect( phrase, Matches( "Make.*pass" ) );
    • Notes 1. Matches may appear only in the body of a constraint expression or when the inherited syntax is used.Collection Constraints (NUnit 2.4 / 2.5)Collection constraints perform tests that are specific to collections. The following collectionconstraints are provided. Before NUnit 2.4.6, these constraints only operated on true Collections.Beginning with 2.4.6, they can work with any object that implements IEnumerable.Beginning with NUnit 2.4.2, use of an improper argument type caused tests to fail. Later releasesgive an error rather than a failure, so that negated constraints will not appear to succeed.For example, both of the following statements give an error in later releases, but the secondwould have succeeded in earlier versions of NUnit.int[] iarray = new int[] { 1, 2, 3 };Assert.That( 5, Is.SubsetOf( iarray ) ); // Fails in early releasesAssert.That( 5, Is.Not.SubsetOf( iarray ) ); /AllItemsConstraintActionApplies a constraint to each item in a collection, succeeding only if all of them succeed.ConstructorAllItemsConstraint(Constraint itemConstraint)SyntaxIs.All...Has.All...Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Is.All.Not.Null );Assert.That( sarray, Is.All.InstanceOf() );Assert.That( iarray, Is.All.GreaterThan(0) );Assert.That( iarray, Has.All.GreaterThan(0) );SomeItemsConstraintActionApplies a constraint to each item in a collection, succeeding if at least one of them succeeds.
    • ConstructorSomeItemsConstraint(Constraint itemConstraint)SyntaxHas.Some...Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Has.Some.GreaterThan(2) );Assert.That( sarray, Has.Some.Length(1) );NoItemConstraintActionApplies a constraint to each item in a collection, succeeding only if all of them fail.ConstructorNoItemConstraint(Constraint itemConstraint)SyntaxHas.None...Has.No...Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Has.None.Null );Assert.That( iarray, Has.No.Null );Assert.That( sarray, Has.None.EqualTo("d") );Assert.That( iarray, Has.None.LessThan(0) );UniqueItemsConstraintActionTests that a collection contains only unique items.ConstructorUniqueItemsConstraint()SyntaxIs.UniqueExample of Usestring[] sarray = new string[] { "a", "b", "c" };Assert.That( sarray, Is.Unique );
    • Notes 1. ??CollectionContainsConstraintActionTests that a collection contains an object.ConstructorCollectionContainsConstraint( object )SyntaxHas.Member( object )Contains.Item( object )Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( iarray, Has.Member(3) );Assert.That( sarray, Has.Member("b") );Assert.That( sarray, Contains.Item("c") );Assert.That( sarray, Has.No.Member("x") );Notes 1. For references, Has.Member uses object equality to find a member in a collection. To check for an object equal to an item the collection, use Has.Some.EqualTo(...).CollectionEquivalentConstraintActionTests that two collections are equivalent - that they contain the same items, in any order.ConstructorCollectionEquivalentConstraint( IEnumerable other )SyntaxIs.EquivalentTo( IEnumerable other )Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "a", "b", "c" };Assert.That( new string[] { "c", "a", "b" }, Is.EquivalentTo( sarray ) );Assert.That( new int[] { 1, 2, 2 }, Is.Not.EquivalentTo( iarray ) );
    • Notes 1. To compare collections for equality, use Is.EqualTo().CollectionSubsetConstraintActionTests that one collection is a subset of another.ConstructorCollectionSubsetConstraint( ICollection )SyntaxIs.SubsetOf( IEnumerable )Example of Useint[] iarray = new int[] { 1, 2, 3 };Assert.That( new int[] { 1, 3 }, Is.SubsetOf( iarray ) );CollectionOrderedConstraint (NUnit 2.5)ActionTests that a collection is ordered.ConstructorCollectionOrderedConstraint()SyntaxIs.OrderedModifiers...Descending...By(string propertyName)...Using(IComparer comparer)...Using(IComparer<T> comparer)...Using(Comparison<T> comparer)Examples of Useint[] iarray = new int[] { 1, 2, 3 };string[] sarray = new string[] { "c", "b", "a" };string[] sarray2 = new string[] ( "a", "aa", "aaa" );Assert.That( iarray, Is.Ordered );Assert.That( sarray, Is.Ordered.Descending );Assert.That( sarray2, Is.Ordered.By("Length");
    • Notes 1. Modifiers may be combined and may appear in any order. If the same modifier is used more than once, the result is undefined. 2. The syntax of Is.Ordered has changed from earlier betas. 3. Property Constraint (NUnit 2.4.2) 4. PropertyConstraint is used to test for existence of a named property and optionally tests its value. It may also be used as a prefix for other constraints to be applied to the property. Syntax Helper Constructor OperationHas.Property( string ) PropertyConstraint( string ) tests that a specific property existsHas.Property( string, PropertyConstraint( string, tests that the value of a property is equalobject ) object ) to the value providedHas.Property( string, applies the following constraint to the PropertyConstraintConstraint)... value of a named property tests that the objects Length property isHas.Length( int ) PropertyConstraint equal to the value given tests that the objects Count property isHas.Count( int ) PropertyConstraint equal to the value givenThrows Constraint (NUnit 2.5)ThrowsConstraint is used to test that some code, represented as a delegate, throws a particularexception. It may be used alone, to merely test the type of constraint, or with an additionalconstraint to be applied to the exception specified as an argument. p>The relatedThrowsNothingConstraint simply asserts that the delegate does not throw an exception.ConstructorsThrowsConstraint(Type expectedType)ThrowsConstraint<T>()ThrowsConstraint(Type expectedType, Constraint constraint)ThrowsConstraint<T>(Constraint constraint)ThrowsNothingConstraint()SyntaxThrows.ExceptionThrows.TargetInvocationExceptionThrows.ArgumentExceptionThrows.InvalidOperationExceptionThrows.TypeOf(Type expectedType)Throws.TypeOf<T>()Throws.InstanceOf(Type expectedType)Throws.InstanceOf<T>()Throws.NothingThrows.InnerException
    • Examples of Use// .NET 1.1Assert.That( new TestDelegate(SomeMethod), Throws.TypeOf(typeof(ArgumentException)));Assert.That( new TestDelegate(SomeMethod), Throws.Exception.TypeOf(typeof(ArgumentException)));Assert.That( new TestDelegate(SomeMethod), Throws.TypeOf(typeof(ArgumentException)) .With.Property("Parameter").EqualTo("myParam"));Assert.That( new TestDelegate(SomeMethod), Throws.ArgumentException );Assert.That( new TestDelegate(SomeMethod), Throws.TargetInvocationException .With.InnerException.TypeOf(ArgumentException));// .NET 2.0Assert.That( SomeMethod, Throws.TypeOf<ArgumentException>());Assert.That( SomeMethod, Throws.Exception.TypeOf<ArgumentException>());Assert.That( SomeMethod, Throws.TypeOf<ArgumentException>() .With.Property("Parameter").EqualTo("myParam"));Assert.That( SomeMethod, Throws.ArgumentException );Assert.That( SomeMethod, Throws.TargetInvocationException .With.InnerException.TypeOf<ArgumentException>());Notes 1. Throws.Exception may be followed by further constraints, which are applied to the exception itself as shown in the last two examples above. It may also be used alone to verify that some exception has been thrown, without regard to type. This is not a recommended practice since you should normally know what exception you are expecting. 2. Throws.TypeOf and Throws.InstanceOf are provided as a shorter syntax for this common test. They work exactly like the corresponding forms following Throws.Exception. 3. Throws.TargetInvocationException/b>, Throws.ArgumentException and Throws.InvalidOperationException provide a shortened form for some common exceptions. 4. Used alone, Throws.InnerException simply tests the InnerException value of the thrown exception. More commonly, it will be used in combination with a test for the type of the outer exception as shown in the examples above.Compound Constraints (NUnit 2.4)Compound constraints are used to combine other constraints in various ways. Syntax Helper Constructor OperationIs.Not... NotConstraint( Constraint ) Negates or reverses the effect of a constraint
    • Tests that all members of a collection matchIs.All... AllItemsConstraint( Constraint ) the constraintConstraint & AndConstraint( Constraint, Tests that both of the constraints are metConstraint Constraint )Constraint | OrConstraint( Constraint, Tests that at least one of the constraints is metConstraint Constraint )Examples of UseAssert.That( 2 + 2, Is.Not.EqualTo( 5 );Assert.That( new int[] { 1, 2, 3 }, Is.All.GreaterThan( 0 ) );Assert.That( 2.3, Is.GreaterThan( 2.0 ) & Is.LessThan( 3.0 ) );Assert.That( 3, Is.LessThan( 5 ) | Is.GreaterThan( 10 ) );// Using inheritanceExpect( 2 + 2, Not.EqualTo( 5 ) );Expect( 2.3, GreaterThan( 2.0 ) & LessThan( 3.0 ) );Delayed Constraint (NUnit 2.5)DelayedConstraint delays the application of another constraint until a certain amount of timehas passed. In its simplest form, it replaces use of a Sleep in the code but it also supports polling,which may allow use of a longer maximum time while still keeping the tests as fast as possible.The After modifier is permitted on any constraint, and the delay applies to the entire expressionup to the point where After appears.Use of a DelayedConstraint with a value argument makes no sense, since the value will beextracted at the point of call. Its intended use is with delegates and references. If a delegate isused with polling, it may be called multiple times so only methods without side effects should beused in this way. Syntax Constructor Operation HelperAfter(int) DelayedConstraint(Constraint, int) tests that a constraint is satisfied after a delay. DelayedConstraint(Constraint, int, tests that a constraint is satisfied after a delayAfter(int, int) int) using polling.List Mapper (NUnit 2.4.2)Unlike Constraint classes, ListMapper is used to modify the actual value argument toAssert.That(). It transforms the actual value, which must be a collection, creating a newcollection to be tested against the supplied constraint. Currently, ListMapper supports onetransformation: creating a collection of property values.
    • Normally, ListMapper will be used through the List.Map() syntax helper or the inherited syntaxequivalent, Map(). The following example shows three forms of the same assert:string[] strings = new string[] { "a", "ab", "abc" };int[] lengths = new int[] { 1, 2, 3 };Assert.That(List.Map(strings).Property("Length"), Is.EqualTo(lengths));Assert.That(new ListMapper(strings).Property("Length"), Is.EqualTo(lengths));// Assuming inheritance from AssertionHelperExpect(Map(strings).Property("Length"), EqualTo(lengths));ReusableConstraint (NUnit 2.5.6)Normally constraints just work. However, attempting to reuse the same constraint in severalplaces can lead to unexpected results.Consider the following code as an example: Constraint myConstraint = Is.Not.Null; Assert.That("not a null", myConstraint); // Passes, of course Assert.That("not a null", myConstraint); // Fails! Whats that about?Well save the technical explanation for later and show the solution first: ReusableConstraint myConstraint = Is.Not.Null; Assert.That("not a null", myConstraint); // Passes Assert.That("not a null", myConstraint); // PassesOr alternatively.. var myConstraint = new ReusableConstraint(Is.Not.Null); Assert.That("not a null", myConstraint); // Passes Assert.That("not a null", myConstraint); // PassesTechnical ExplanationIn the original example, the value assigned to myConstraint is known as an unresolvedconstraint. In fact, its an unresolved NullConstraint, because that was the last constraintencountered in the expression. Its associated with a Not operator that has not yet been applied.Thats OK for use with Assert.That(), because the method knows how to resolve a constraintbefore using it. Assert.That() resolves this constraint to a NotConstraint referencing the originalNullConstraint.Of course, the original reference in myConstraint is left unchanged in all of this. But theEqualConstraint it points to has now been resolved. It is now a resolved constraint and cant be
    • resolved again by the second Assert.That(), which only sees the NullConstraint and not theNotConstraint.So, for reusability, what we want to save is the result of resolving the constraint, in this case NotConstraint => NullConstraintThats what ReusableConstraint does for us. It resolves the full expression and saves the result. Then itpasses all operations on to that saved result.When to Use ItUse this constraint any time you want to reuse a constraint expression and youll be safe.If you like to take chances, youll find that you can avoid using it in the following cases... 1. With a simple constraint involving no operators, like... 2. Constraint myConstraint = Is.Null; 3. Constraint myConstraint = Is.EqualTo(42); 4. With any constraint you construct using new, without using the "dotted" constraint syntax... 5. Constraint myConstraint = new NotConstraint(new NullConstraint()); 6. Constraint myConstraint = new AndConstraint( 7. new GreaterThanConstraint(0), 8. new LessThanConstraint(100)); However, there is no significant penalty to using ReusableConstraint. It makes your intent much clearer and the exceptions listed are accidents of the internal implementation and could disappear in future releases.AttributesVersion 1 of NUnit used the classic approach to identifying tests based on inheritance andnaming conventions. From version 2.0 on, NUnit has used custom attributes for this purpose.Because NUnit test fixtures do not inherit from a framework class, the developer is free to useinheritance in other ways. And because there is no arbitrary convention for naming tests, thechoice of names can be entirely oriented toward communicating the purpose of the test.All NUnit attributes are contained in the NUnit.Framework namespace. Each source file thatcontains tests must include a using statement for that namespace and the project must referencethe framework assembly, nunit.framework.dll.Beginning with NUnit 2.4.6, NUnits attributes are no longer sealed and any attributes that derivefrom them will be recognized by NUnit.
    • CategoryAttribute (NUnit 2.2)The Category attribute provides an alternative to suites for dealing with groups of tests. Eitherindividual test cases or fixtures may be identified as belonging to a particular category. Both thegui and console test runners allow specifying a list of categories to be included in or excludedfrom the run. When categories are used, only the tests in the selected categories will be run.Those tests in categories that are not selected are not reported at all.This feature is accessible by use of the /include and /exclude arguments to the console runner andthrough a separate "Categories" tab in the gui. The gui provides a visual indication of whichcategories are selected at any time.Test Fixture Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [Category("LongRunning")] public class LongRunningTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Category("LongRunning")> Public Class LongRunningTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] [Category("LongRunning")] public __gc class LongRunningTests { // ... };}#include "cppsample.h"
    • namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Category("LongRunning") */public class LongRunningTests{ // ...}Test Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Category("Long")] public void VeryLongTest() { /* ... */ }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Category("Long")> Public Sub VeryLongTest() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [Test][Category("Long")] void VeryLongTest(); };}
    • #include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Category("Long") */ public void VeryLongTest() { /* ... */ }}Custom Category AttributesBeginning with NUnit 2.4, it is possible to define custom attributes that derive fromCategoryAttribute and have them recognized by NUnit. The default protected constructor ofCategoryAttribute sets the category name to the name of your class.Heres an example that creates a category of Critical tests. It works just like any other category,but has a simpler syntax. A test reporting system might make use of the attribute to providespecial reports.[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]public class CriticalAttribute : CategoryAttribute { }...[Test, Critical]public void MyTest(){ /*...*/ }CombinatorialAttribute (NUnit 2.5)The CombinatorialAttribute is used on a test to specify that NUnit should generate test casesfor all possible combinations of the individual data items provided for the parameters of a test.Since this is the default, use of this attribute is optional.ExampleThe following test will be executed six times, as follows: MyTest(1, "A") MyTest(1, "B")
    • MyTest(2, "A") MyTest(2, "B") MyTest(3, "A") MyTest(3, "B")[Test, Combinatorial]public void MyTest( [Values(1,2,3)] int x, [Values("A","B")] string s){ ...}CultureAttribute (NUnit 2.4.2)The Culture attribute is used to specify cultures for which a test or fixture should be run. It doesnot affect the culture setting, but merely uses it to determine whether to run the test. If you wishto change the culture when running a test, use the SetCulture attribute instead.If the specified culture requirements for a test are not met it is skipped. In the gui, the tree nodefor the test remains gray and the status bar color is not affected.One use of the Culture attribute is to provide alternative tests under different cultures. You mayspecify either specific cultures, like "en-GB" or neutral cultures like "de".Test Fixture Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [Culture("fr-FR")] public class FrenchCultureTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Culture("fr-FR")> Public Class FrenchCultureTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;
    • namespace NUnitTests{ [TestFixture] [Culture("fr-FR")] public __gc class FrenchCultureTests { // ... };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Culture("fr-FR") */public class FrenchCultureTests{ // ...}Test Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Culture(Exclude="en,de")] public void SomeTest() { /* ... */ }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Culture(Exclude="en,de")> Public Sub SomeTest() ... End Sub End ClassEnd Namespace
    • #using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [Test][Culture(Exclude="en,de")] void SomeTest(); };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Culture(Exclude=en,de") */ public void SomeTest() { /* ... */ }}DatapointAttribute / DatapointsAttribute (NUnit 2.5) (Experimental)The Datapoint and Datapoints attributes are used to provide data for Theories and are ignoredfor ordinary tests - including tests with parameters.DataPointAttributeWhen a Theory is loaded, NUnit creates arguments for each of its parameters by using any fieldsof the same type as the parameter annotated with the DatapointAttribute. Fields must bemembers of the class containing the Theory and their Type must exactly match the argument forwhich data is being supplied.DataPointsAttributeIn addition to specifying individual datapoints, collections of datapoints may be provided by useof the DatapointsAttribute - note the spelling. This attribute may be placed on methods orproperties in addition to fields. The returned value must be either an array of the required type or(beginning with NUnit 2.5.5) an IEnumerable<T> returning an enumeration of the requiredtype. The data Type must exactly match the argument for which data is being supplied.
    • Automatically Supplied DatapointsIt is normally not necessary to specify datapoints for boolean or enum arguments. Beginningwith version 2.5.4, NUnit automatically supplies values of true and false for boolean argumentsand will supply all defined values of any enumeration.If for some reason you dont wish to use all possible values, you can override this behavior bysupplying your own datapoints. If you supply any datapoints for an argument, automaticdatapoint generation is suppressed.Description (NUnit 2.4)The Description attribute is used to apply descriptive text to a Test, TestFixture or Assembly.The text appears in the XML output file and is shown in the Test Properties dialog.Example:[assembly: Description("Assembly description here")]namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture, Description("Fixture description here")] public class SomeTests { [Test, Description("Test description here")] public void OneTest() { /* ... */ } }}<assembly: Description("Assembly description here")>Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Description("Fixture description here")>_ Public Class SomeTests <Test(), Description("Test description here")>_ Public Sub OneTest() ... End Sub End ClassEnd Namespace[assembly:Description("Assembly description here")]#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;
    • namespace NUnitTests{ [TestFixture, Description("Fixture description here")] public __gc class SomeTests { [Test, Description("Test description here")] void OneTest(); };}#include "cppsample.h"namespace NUnitTests { // ...}/** @assembly NUnit.Framework.Description("Assembly description here") */package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Description("Fixture description here") */public class SomeTests{ /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Description("Test description here") */ public void OneTest() { /* ... */ }}Note: The Test and TestFixture attributes continue to support an optional Description property.The Description attribute should be used for new applciations. If both are used, the Descriptionattribute takes precedence.ExpectedExceptionAttribute (NUnit 2.0 plus Updates)This is the way to specify that the execution of a test will throw an exception. This attribute has anumber of positional and named parameters, which we will discuss in separate sectionsaccording to the purpose they serve.Specifying the Expected Exception TypeThe original attribute, introduced with NUnit 2.0 took a single argument giving the exact type ofthe expected exception. For example...[ExpectedException( typeof( ArgumentException ) )]public void TestMethod(){...
    • Beginning with NUnit 2.2.4, it became possible to specify the type of exception as a string,avoiding the need for a reference to the defining assembly...[ExpectedException( "System.ArgumentException" ) )]public void TestMethod(){...The above two examples function identically: the test only succeeds if a System.Argumentexception is thrown.Specifying the Expected MessageNUnit 2.1 introduced a constructor with a second argument, specifying the exact text of themessage property of the exception. After NUnit 2.2.4, the same extension was made to theconstructor taking a string argument. With NUnit 2.4, these arguments are marked obsolete, anda named parameter is provided instead...// Obsolete form:[ExpectedException( typeof( ArgumentException ), "expected message" )][ExpectedException( "System.ArgumentException", "expected message" )]// Prefered form:[ExpectedException( typeof( ArgumentException ), ExpectedMessage="expectedmessage" )][ExpectedException( "System.ArgumentException", ExpectedMessage="expectedmessage" )]With NUnit 2.4, it is possible to specify additional tests on the exception message, beyond asimple exact match. This is done using the MatchType named parameter, whose argument is anenumeration, defined as follows:public enum MessageMatch{ /// Expect an exact match Exact, /// Expect a message containing the parameter string Contains, /// Match the regular expression provided as a parameter Regex, /// Expect a message starting with the parameter string StartsWith}The following example is for a test that passes only if an ArgumentException with a messagecontaining "unspecified" is received.[ExpectedException( typeof( ArgumentException),ExpectedMessage="unspecified", MatchType=MessageMatch.Contains )]public void TestMethod(){
    • ...If MatchType is not specified, an exact match is used as before.Specifying a Custom Error MessageWith NUnit 2.4, it is possible to specify a custom message to be displayed if theExpectedException attribute is not satisfied. This is done through the UserMessage namedparameter...[ExpectedException( typeof( ArgumentException ), UserMessage="Custom message")]public void TestMethod(){...Handling the Exception in CodeIf the processing required for an exception is too complex to express in the attribute declaration,the normal practice is to process it in the test code using a try/catch block. As an alternative,NUnit 2.4 allows designating a method that will be called to process the exception. This isparticularly useful when multiple exceptions need to be processed in the same way.An common exception handler may be designated by implementing theIExpectExceptionInterface, which is defined as follows...public interface IExpectException{ void HandleException( System.Exception ex );}The exception handler is only called for methods marked with the ExpectedException attribute.If all checks - including the type of the exception - are to be performed in code, the attribute maybe specified without any arguments in order to indicate that an exception is expected.An handler may be designated for a particular method using the Handler named parameter.[ExpectedException( Handler="HandlerMethod" )]public void TestMethod(){...}public void HandlerMethod( System.Exception ex ){...}
    • This technique may be used without implementing IExpectException or in combination with it.In the latter case, the designated handler applies to any method that specifies it, while the normalexception handler applies to any other methods that specify an ExpectedException.However it is specified, the handler method should examine the exception and Assert onwhatever properties are relevant. Any resulting failure message will then be consistent in formatwith other assertions performed in the tests.Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [ExpectedException(typeof(InvalidOperationException))] public void ExpectAnExceptionByType() { /* ... */ } [Test] [ExpectedException("System.InvalidOperationException")] public void ExpectAnExceptionByName() { /* ... */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), ExpectedException(GetType(Exception))> Public Sub ExpectAnExceptionByType() ... End Sub <TestFixture()> Public Class SuccessTests <Test(), ExpectedException("System.Exception")> Public Sub ExpectAnExceptionByName() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{
    • [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 forrunning. The test or fixture will be run if it is selected in the gui, if its name is specified on theconsole 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 isskipped unless it has been specifically selected by one of the above means. The test does notaffect the outcome of the run at all: it is not considered as ignored and is not even counted in thetotal number of tests. In the gui, the tree node for the test remains gray and the status bar color isnot affected.Note: In versions of NUnit prior to 2.4, these tests were shown as ignored.Test Fixture Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture, Explicit] public class ExplicitTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests
    • <TestFixture(), Explicit()> Public Class ExplicitTests ... End ClassEnd 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 Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test, Explicit] public void ExplicitTest() { /* ... */ }}Imports SystemImports Nunit.Framework
    • Namespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Explicit()> Public Sub ExplicitTest() ... End Sub End ClassEnd 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 personmarks either a Test or a TestFixture with the Ignore Attribute. The running program sees theattribute and does not run the test or tests. The progress bar will turn yellow if a test is not runand 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 mechanismthan commenting out the test or renaming methods, since the tests will be compiled with the restof the code and there is an indication at run time that a test is not being run. This insures thattests will not be forgotten.
    • Test Fixture Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [Ignore("Ignore a fixture")] public class SuccessTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Ignore("Ignore a fixture")> Public Class SuccessTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] [Ignore("Ignore a fixture")] public __gc class SuccessTests { // ... };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Ignore("Ignore a fixture") */public class SuccessTests{ // ...}
    • Test Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Ignore("Ignore a test")] public void IgnoredTest() { /* ... */ }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Ignore("Ignore a test")> Public Sub Ignored() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [Test][Ignore("Ignore a test")] void IgnoredTest(); };}#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.Ignore("ignored test") */ public void IgnoredTest() { /* ... */ }}MaxtimeAttribute (NUnit 2.5)The MaxtimeAttribute is used on test methods to specify a maximum time in milliseconds for atest case. If the test case takes longer than the specified time to complete, it is reported as afailure.Example[Test, Maxtime(2000)]public void TimedTest(){ ...}Notes: 1. Any assertion failures take precedence over the elapsed time check. 2. This attribute does not cancel the test if the time is exceeded. It merely waits for the test to complete and then compares the elapsed time to the specified maximum. If you want to cancel long-running testsPairwiseAttribute (NUnit 2.5)The PairwiseAttribute is used on a test to specify that NUnit should generate test cases in sucha way that all possible pairs of values are used. This is a well-known approach for combatting thecombinatorial explosion of test cases when more than two features (parameters) are involved.Note: In the current Alpha release, this attribute is accepted but ignored and data items arecombined usin the default combinatorial approach.PlatformAttribute (NUnit 2.2.2)The Platform attribute is used to specify platforms for which a test or fixture should be run.Platforms are specified using case-insensitive string values and may be either included orexcluded from the run by use of the Include or Exclude properties respectively. Platforms to beincluded may alternatively be specified as an argument to the PlatformAttribute constructor. Ineither case, multiple comma-separated values may be specified.If a test or fixture with the Platform attribute does not satisfy the specified platform requirementsit is skipped. The test does not affect the outcome of the run at all: it is not considered as ignoredand is not even counted in the total number of tests. In the gui, the tree node for the test remainsgray 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 Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [Platform("NET-2.0")] public class DotNetTwoTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Platform("NET-2.0")> Public Class DotNetTwoTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] [Platform("NET-2.0")] public __gc class DotNetTwoTests { // ... };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Platform("NET-2.0") */public class DotNetTwoTests{ // ...}
    • Test Syntaxnamespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] [Platform(Exclude="Win98,WinME")] public void SomeTest() { /* ... */ }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test(), Platform(Exclude="Win98,WinME")> Public Sub SomeTest() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [Test][Platform(Exclude="Win98,WinME")] 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.Platform(Exclude="Win98,WinME") */ public void SomeTest() { /* ... */ }}Platform SpecifiersThe following values are recognized as platform specifiers. They may be expressed in upper,lower or mixed case. Win Win32 Win32S Win32Windows Win32NT WinCE Win95 Win98 WinMe NT3 NT4 NT5 NT6 Win2K WinXP Win2003Server Vista Win2008Server Unix Linux Net Net-1.0 Net-1.1 Net-2.0 Net-4.0 NetCF SSCLI Rotor Mono Mono-1.0 Mono-2.0PropertyAttribute (NUnit 2.4)The Property attribute provides a generalized approach to setting named properties on any testcase or fixture, using a name/value pair.
    • In the example below, the fixture class MathTests is given a Location value of 723 while the testcase AdditionTest is given a Severity of "Critical"Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture, Property("Location",723)] public class MathTests { [Test, Property("Severity", "Critical")] public void AdditionTest() { /* ... */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), Property("Location",723)> Public Class MathTests <Test(), Property("Severity","Critical")> Public Sub AdditionTest() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture, Property("Location",723)] public __gc class MathTests { [Test, Property("Severity","Critical")] void AdditionTest(); };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;
    • import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() *//** @attribute NUnit.Framework.Property("Location",723) */public class MathTests{ /** @attribute NUnit.Framework.Test() */ /** @attribute NUnit.Framework.Property("Severity","Critical") */ public void AdditionTest() { /* ... */ }}Usage NoteThe PropertyAttribute is not used for any purpose by NUnit itself, but it does display them in theXML output file and in the Test Properties dialog of the gui.It is possible to write extensions that access the value of specific properties. It is also possible toaccess the value of properties from within a test using reflection.Custom Property AttributesUsers can define custom attributes that derive from PropertyAttribute and have themrecognized by NUnit. PropertyAttribute provides a protected constructor that takes the value ofthe property and sets the property name to the name of the derived class. NUnit itself uses thisfacility: some of its specialized attributes are actually specializations of PropertyAttribute.Heres an example that creates a Severity property. It works just like any other property, but has asimpler syntax and is type-safe. A test reporting system might make use of the property toprovide special reports.public enum SeverityLevel{ Critical, Major, Normal, Minor}[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]public class SeverityAttribute : PropertyAttribute{ public SeverityAttribute( SeverityLevel level ) : base( level );}...[Test, Severity( SeverityLevel.Critical)]public void MyTest()
    • { /*...*/ }Beginning with NUnit 2.5, a property attribute is able to contain multiple name/value pairs. Thiscapability is not exposed publicly but may be used by derived property classes. NUnit uses thisfeature itself for certain attributes.RandomAttribute (NUnit 2.5)The RandomAttribute is used to specify a set of random values to be provided for an individualparameter of a parameterized test method. Since NUnit combines the data provided for eachparameter into a set of test cases, data must be provided for all parameters if it is provided forany of them.By default, NUnit creates test cases from all possible combinations of the datapoints provided onparameters - the combinatorial approach. This default may be modified by use of specificattributes on the test method itself.RandomAttribute supports the following constructors:public Random( int count );public Random( double min, double max, int count );public Random( int min, int max, int count );ExampleThe following test will be executed fifteen times, three times for each value of x, each combinedwith 5 random doubles from -1.0 to +1.0.[Test]public void MyTest( [Values(1,2,3)] int x, [Random(-1.0, 1.0, 5)] double d){ ...}RangeAttribute (NUnit 2.5)The RangeAttribute is used to specify a range of values to be provided for an individualparameter of a parameterized test method. Since NUnit combines the data provided for eachparameter into a set of test cases, data must be provided for all parameters if it is provided forany of them.By default, NUnit creates test cases from all possible combinations of the datapoints provided onparameters - the combinatorial approach. This default may be modified by use of specificattributes on the test method itself.
    • RangeAttribute supports the following constructors:public RangeAttribute( int from, int to );public RangeAttribute( int from, int to, int step );public RangeAttribute( long from, long to, long step );public RangeAttribute( float from, float to, float step );public RangeAttribute( double from, double to, double step );ExampleThe following test will be executed nine times, as follows: MyTest(1, 0.2) MyTest(1, 0.4) MyTest(1, 0.6) MyTest(2, 0.2) MyTest(2, 0.4) MyTest(2, 0.6) MyTest(3, 0.2) MyTest(3, 0.4) MyTest(3, 0.6)[Test]public void MyTest( [Values(1,2,3) int x, [Range(0.2,0.6,0.2] double d){ ...}RepeatAttribute (NUnit 2.5)RepeatAttribute is used on a test case to specify that it should be executed multiple times. Ifany repetition fails, the remaining ones are not run and a failure is reported.RequiredAddinAttribute (NUnit 2.5)The RequiredAddin attribute is used to indicate that an assembly requires a particular addin inorder to function correctly. If that addin is not installed, the entire assembly is marked as non-runnable.Note: In the Alpha-3 release, this attribute may be applied to classes or methods as well. This isof limited utility, for two reasons: 1. If the method or class is not recognized as a test, due to the addin being missing, then NUnit will never process it. 2. If the method or class is handled by some a different addin, that addin may not recognize the attribute.The attribute will be limited to assemblies only in the next release.
    • Example[assembly: RequiredAddin("MyTestFixtureAddin")][assembly: RequiredAddin("MyTestAddin")][assembly: RequiredAddin("MyDecoratorAddin")]...namespace NUnit.Tests{ using System; using NUnit.Framework; [MyTestFixture] public class MyTests { [MyTest] public void SomeTest() { ... } } [TestFixture, MyDecorator] public class MoreTests { [Test, MyDecorator] public void AnotherTest() { ... } }}RequiresMTAAttribute (NUnit 2.5)The RequiresMTAAttribute is used on a test method, class or assembly to specify that the testsshould be run in the multi-threaded apartment. It causes creation of a new thread if the parent testis not already running in the MTA.Note: On test methods, you may also use the MTAThreadAttribute. Although the runtime onlyrecognizes this attribute on the entrypoint of an executable assembly, many users have expectedit to work on tests, so we treat it as a synonym.Examples// An MTA thread will be created and used to run// all the tests in the assembly[assembly:RequiresMTA]...// TestFixture requiring a separate thread[TestFixture, RequiresMTA]public class FixtureRequiringMTA
    • { // An MTA thread will be created and all // tests in the fixture will run on it // unless the containing assembly is // already running on an MTA Thread}[TestFixture]public class AnotherFixture{ [Test, RequiresMTA] public void TestRequiringMTA() { // A separate thread will be created for this test // unless the containing fixture is already running // in the MTA. }}RequiresSTAAttribute (NUnit 2.5)The RequiresSTAAttribute is used on a test method, class or assembly to specify that the testsshould be run in the Single-threaded apartment. It causes creation of a new thread if the parenttest is not already running in the STA.Note: On test methods, you may also use the STAThreadAttribute. Although the runtime onlyrecognizes this attribute on the entrypoint of an executable assembly, many users have expectedit to work on tests, so we treat it as a synonym.Examples// An STA thread will be created and used to run// all the tests in the assembly[assembly:RequiresSTA]...// TestFixture requiring a separate thread[TestFixture, RequiresSTA]public class FixtureRequiringSTA{ // An STA thread will be created and all // tests in the fixture will run on it // unless the containing assembly is // already running on an STA Thread}[TestFixture]public class AnotherFixture{ [Test, RequiresSTA] public void TestRequiringSTA() {
    • // A separate thread will be created for this test // unless the containing fixture is already running // in the STA. }}RequiresThreadAttribute (NUnit 2.5)The RequiresThreadAttribute is used to indicate that a test method, class or assembly shouldbe run on a separate thread. Optionally, the desired apartment for the thread may be specified inthe constructor.Note: This attribute, used with or without an ApartmentState argument will always result increation of a new thread. To create a thread only if the current ApartmentState is not appropriate,use RequiresSTAAttribute or RequiresMTAAttribute.Examples// A thread will be created and used to run// all the tests in the assembly[assembly:RequiresThread]...// TestFixture requiring a separate thread[TestFixture, RequiresThread]public class FixtureOnThread{ // A separate thread will be created and all // tests in the fixture will run on it.}[TestFixture]public class AnotherFixture{ [Test, RequiresThread] public void TestRequiringThread() { // A separate thread will be created for this test } [Test, RequiresThread(ApartmentState.STA)] public void TestRequiringSTAThread() { // A separate STA thread will be created for tnis test. }}
    • SequentialAttribute (NUnit 2.5)The SequentialAttribute is used on a test to specify that NUnit should generate test cases byselecting individual data items provided for the parameters of the test, without generatingadditional combinations.Note: If parameter data is provided by multiple attributes, the order in which NUnit uses the dataitems is not guaranteed. However, it can be expected to remain constant for a given runtime andoperating system.ExampleThe following test will be executed three times, as follows: MyTest(1, "A") MyTest(2, "B") MyTest(3, null)[Test, Sequential]public void MyTest( [Values(1,2,3)] int x, [Values("A","B")] string s){ ...}SetCultureAttribute (NUnit 2.4.2)The SetCulture attribute is used to set the current Culture for the duration of a test. It may bespecified at the level of a test or a fixture. The culture remains set until the test or fixturecompletes and is then reset to its original value. If you wish to use the current culture setting todecide whether to run a test, use the Culture attribute instead of this one.Only one culture may be specified. Running a test under multiple cultures is a planned futureenhancement. At this time, you can achieve the same result by factoring out your test code into aprivate method that is called by each individual test method.Examples:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [SetCulture("fr-FR")] public class FrenchCultureTests { // ... }
    • }Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture(), SetCulture("fr-FR")> Public Class FrenchCultureTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] [SetCulture("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.SetCulture("fr-FR") */public class FrenchCultureTests{ // ...}SetUpAttribute (NUnit 2.0 / 2.5)This attribute is used inside a TestFixture to provide a common set of functions that areperformed just before each test method is called.Before NUnit 2.5, a TestFixture could have only one SetUp method and it was required to be aninstance method.Beginning with NUnit 2.5, SetUp methods may be either static or instance methods and youmay define more than one of them in a fixture. Normally, multiple SetUp methods are onlydefined at different levels of an inheritance hierarchy, as explained below.
    • If a SetUp method fails or throws an exception, the test is not executed and a failure or error isreported.Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [SetUp] public void Init() { /* ... */ } [TearDown] public void Cleanup() { /* ... */ } [Test] public void Add() { /* ... */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <SetUp()> Public Sub Init() ... End Sub <TearDown()> Public Sub Cleanup() ... End Sub <Test()> Public Sub Add() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [SetUp] void Init(); [TearDown] void Cleanup();
    • [Test] void Add(); };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.SetUp() */ public void Init() { /* ... */ } /** @attribute NUnit.Framework.TearDown() */ public void Cleanup() { /* ... */ } /** @attribute NUnit.Framework.Test() */ public void Add() { /* ... */ }}InheritanceThe SetUp attribute is inherited from any base class. Therefore, if a base class has defined aSetUp method, that method will be called before each test method in the derived class.Before NUnit 2.5, you were permitted only one SetUp method. If you wanted to have someSetUp functionality in the base class and add more in the derived class you needed to call thebase class method yourself.With NUnit 2.5, you can achieve the same result by defining a SetUp method in the base classand another in the derived class. NUnit will call base class SetUp methods before those in thederived classes.Note: Although it is possible to define multiple SetUp methods in the same class, you shouldrarely do so. Unlike methods defined in separate classes in the inheritance hierarchy, the order inwhich they are executed is not guaranteed.
    • SetUpFixtureAttribute (NUnit 2.4)This is the attribute that marks a class that contains the one-time setup or teardown methods forall the test fixtures under a given namespace. The class may contain at most one method markedwith the SetUpAttribute and one method marked with the TearDownAttribute.There are a few restrictions on a class that is used as a setup fixture. It must be a publicly exported type or NUnit will not see it. It must have a default constructor or NUnit will not be able to construct it.The SetUp method in a SetUpFixture is executed once before any of the fixtures contained in itsnamespace. The TearDown method is executed once after all the fixtures have completedexecution. In the examples below, the method RunBeforeAnyTests() is called before any tests orsetup methods in the NUnit.Tests namespace. The method RunAfterAnyTests() is called after allthe tests in the namespace as well as their individual or fixture teardowns have completedexection.Only one SetUpFixture should be created in a given namespace. A SetUpFixture outside of anynamespace provides SetUp and TearDown for the entire assembly.Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [SetUpFixture] public class MySetUpClass { [SetUp] RunBeforeAnyTests() { // ... } [TearDown] RunAfterAnyTests() { // ... } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class MySetUpClass
    • <SetUp()> Public Sub RunBeforeAnyTests() ... End Sub <TearDown()> Public Sub RunAfterAnyTests() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class MySetUpClass { [SetUp] public void RunBeforeAnyTests(); [TearDown] public void RunAfterAnyTests(); };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class MySetUpClass{ /** @attribute NUnit.Framework.SetUp() */ public void RunBeforeAnyTests() { /* ... */ } /** @attribute NUnit.Framework.TearDown() */ public void RunAfterAnyTests() { /* ... */ }}SuiteAttribute (NUnit 2.0/2.4.4)The Suite Attribute is used to define subsets of test to be run from the command-line, using the/fixture option. It was introduced in NUnit 2.0 to replace the older approach of inheriting fromthe TestSuite class.Originally, the NUnit developers believed that the need for the Suite mechanism would diminishbecause of the dynamic creation of suites based on namespaces. It was provided for backwardscompatibility.
    • That has not proven to be true. Suites are still used today by many people, so we are making aneffort to revive them in terms of usability.The Suite mechanism depends on a static property marked with the SuiteAttribute. In the clasicimplementation, supported by all releases since 2.0, that property returns a TestSuite, populatedwith the tests that are to be executed.Old Approachnamespace NUnit.Tests{ using System; using NUnit.Framework; using NUnit.Core; public class AllTests { [Suite] public static TestSuite Suite { get { TestSuite suite = new TestSuite("All Tests"); suite.Add(new OneTestCase()); suite.Add(new Assemblies.AssemblyTests()); suite.Add(new AssertionTest()); return suite; } } }}This approach has a serious problem: it requires a reference to the nunit.core assembly, which isnot normally referenced by user tests. This means that the tests cannot be ported across versionsof NUnit without recompilation. In some cases, introducing more than one version of the coreassembly can prevent NUnit from running correctly.Beginning with NUnit 2.4.4, a new approach is available. The property marked with theSuiteAttribute may simply return a collection containing test fixture objects or Types. If a Typeis provided, NUnit creates an object of that type for use as a fixture. Any other object is assumedto be a pre-created fixture object. This allows objects with parameterized constructors or settableproperties to be used as fixtures.Test suites created through use of the SuiteAttribute may contain TestFixtureSetUp andTestFixtureTearDown methods, to perform one-time setup and teardown for the tests includedin the suite.New Approach - Fixture Objectsnamespace NUnit.Tests{ using System; using NUnit.Framework;
    • private class AllTests { [Suite] public static IEnumerable Suite { get { ArrayList suite = new ArrayList(); suite.Add(new OneTestCase()); suite.Add(new AssemblyTests()); suite.Add(new NoNamespaceTestFixture()); return suite; } } }}New Approach - Fixture Typesnamespace NUnit.Tests{ using System; using NUnit.Framework; private class AllTests { [Suite] public static IEnumerable Suite { get { ArrayList suite = new ArrayList(); suite.Add(typeof(OneTestCase)); suite.Add(typeof(AssemblyTests)); suite.Add(typeof(NoNamespaceTestFixture)); return suite; } } }}LimitationsNUnit support for user-defined Suites currently has two limitations: 1. It is not possible to include individual test cases directly in a Suite using the new approach. Anyone wanting to do so will need to use the old approach and create an object derive from NUnit.Core.TestCase. This is not recommended, since it requires a reference to the core assembly. 2. Suites are currently not displayed in the Gui or run automatically by either runner when they are encountered. The historical purpose of the Suite mechanism was to provide a way of aggregating tests at the top level of each run. Hence, they are only supported when used with the /fixture option on the console or gui command line.
    • Approaches to removing these limitations are being investigated as part of the planning forfuture NUnit releases.TearDownAttribute (NUnit 2.0 / 2.5)This attribute is used inside a TestFixture to provide a common set of functions that areperformed after each test method is run.Before NUnit 2.5, a TestFixture could have only one TearDown method and it was required tobe an instance method.Beginning with NUnit 2.5, TearDown methods may be either static or instance methods and youmay define more than one of them in a fixture. Normally, multiple TearDown methods are onlydefined at different levels of an inheritance hierarchy, as explained below.So long as any SetUp method runs without error, the TearDown method is guaranteed to run. Itwill not run if a SetUp method fails or throws an exception.Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [SetUp] public void Init() { /* ... */ } [TearDown] public void Cleanup() { /* ... */ } [Test] public void Add() { /* ... */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <SetUp()> Public Sub Init() ... End Sub <TearDown()> Public Sub Cleanup() ... End Sub
    • <Test()> Public Sub Add() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [SetUp] void Init(); [TearDown] void Cleanup(); [Test] void Add(); };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.SetUp() */ public void Init() { /* ... */ } /** @attribute NUnit.Framework.TearDown() */ public void Cleanup() { /* ... */ } /** @attribute NUnit.Framework.Test() */ public void Add() { /* ... */ }}InheritanceThe TearDown attribute is inherited from any base class. Therefore, if a base class has defined aTearDown method, that method will be called after each test method in the derived class.
    • Before NUnit 2.5, you were permitted only one TearDown method. If you wanted to have someTearDown functionality in the base class and add more in the derived class you needed to callthe base class method yourself.With NUnit 2.5, you can achieve the same result by defining a TearDown method in the baseclass and another in the derived class. NUnit will call base class TearDown methods after thosein the derived classes.Note: Although it is possible to define multiple TearDown methods in the same class, youshould rarely do so. Unlike methods defined in separate classes in the inheritance hierarchy, theorder in which they are executed is not guaranteed.TestAttribute (NUnit 2.0 / 2.5)The Test attribute is one way of marking a method inside a TestFixture class as a test. Forbackwards compatibility with previous versions of Nunit a test method may also be found if thefirst 4 letters are "test" regardless of case. This option is available by setting a value in the configfile for the test.Prior to NUnit 2.5, the signature for a test method was: public void MethodName()Beginning with NUnit 2.5, static methods may be used as tests: public static void MethodName()In addition, with 2.5, test methods may have arguments and return values, provided that NUnit istold what values to use for the arguments and how to handle the return value. For moreinformation on these capabilities, see Parameterized Tests as well as some of the relatedattributes listed at the end of this page.Parameterized test methods may also be generic, provided that NUnit is able to deduce theproper argument types from the types of the data arguments supplied.If the programmer marks a test method that does not have the correct signature it will beconsidered as not runnable and be indicated as such by the console or gui runner. In the Gui,such tests are marked in red.In the examples on this page, NUnit would have no way of knowing what values to supply asarguments, so methods without parameters are used.Example:namespace NUnit.Tests{
    • using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [Test] public void Add() { /* ... */ } public void TestSubtract() { /* backwards compatibility */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <Test()> Public Sub Add() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [Test] void Add(); };}#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() */ public void Add() { /* ... */ }}
    • Parameterized TestsNUnit 2.5 supports parameterized tests. Test methods may have parameters and variousattributes are available to indicate what arguments should be supplied by NUnit.Multiple sets of arguments cause the creation of multiple tests. All arguments are created at thepoint of loading the tests, so the individual test cases are available for display and selection in theGui, if desired.Some attributes allow you to specify arguments inline - directly on the attribute - while othersuse a separate method, property or field to hold the arguments. In addition, some attributesidentify complete test cases, including all the necessary arguments, while others only providedata for a single argument. This gives rise to four groups of attributes, as shown in the followingtable. Complete Test Cases Data for One Argument RandomAttribute Inline TestCaseAttribute RangeAttribute ValuesAttributeSeparate TestCaseSourceAttribute ValueSourceAttributeIn addition, when data is specified for individual arguments, special attributes may be added tothe test method itself in order to tell NUnit how to go about combining the arguments. Currently,the following attributes are provided: CombinatorialAttribute (default) PairwiseAttribute SequentialAttributeOrder of ExecutionIn NUnit 2.5, individual test cases are sorted alphabetically and executed in that order. WithNUnit 2.5.1, the individual cases are not sorted, but are executed in the order in which NUnitdiscovers them. This order does not follow the lexical order of the attributes and will often varybetween different compilers or different versions of the CLR.The following specific rules for ordering apply: 1. If all arguments are specified in a single TestCaseSource attribute, the ordering of the cases provided will be maintained. 2. If each parameter has a single Values, ValueSource or Range attribute and the Sequential combining strategy is used - or there is only one argument - the ordering will be maintained.
    • 3. In all other cases, including using multiple TestCase attributes or a combination of different types of attributes, the ordering of the test cases is undefined.TestCaseAttribute (NUnit 2.5)TestCaseAttribute serves the dual purpose of marking a method with parameters as a testmethod and providing inline data to be used when invoking that method. Here is an example of atest being run three times, with three different sets of data:[TestCase(12,3,4)][TestCase(12,2,6)][TestCase(12,4,3)]public void DivideTest(int n, int d, int q){ Assert.AreEqual( q, n / d );}Note: Because arguments to .NET attributes are limited in terms of the Types that may be used,NUnit will make some attempt to convert the supplied values using Convert.ChangeType()before supplying it to the test.TestCaseAttribute may appear one or more times on a test method, which may also carry otherattributes providing test data, such as the FactoriesAttribute. The method may optionally bemarked with the TestAttribute as well.By using the named parameter Result this test set may be simplified further:[TestCase(12,3, Result=4)][TestCase(12,2, Result=6)][TestCase(12,4, Result=3)]public int DivideTest(int n, int d){ return( n / d );}In the above example, NUnit checks that the return value of the method is equal to the expectedresult provided on the attributTestCaseAttribute supports a number of additional named parameters, which may be used asfollows:Description Sets the description property of the testExpectedException Specifies a the Type of an exception that should be thrown by this invocation
    • ExpectedExceptionName Specifies a the FullName of an exception that should be thrown by this invocationExpectedMessage Specifies the message text of the expected exceptionMatchType A MessageMatch enum value indicating how to test the expected message (See ExpectedExceptionAttribute)Result The expected result to be returned from the method, which must have a compatible return type.TestName Provides a name for the test. If not specified, a name is generated based on the method name and the arguments provided.Ignore Set to true in order to ignore the individual test case.IgnoreReason Specifies the reason for ignoring this test case. If set to a non-empty string, then Ignore is assumed to be true.Order of ExecutionIn NUnit 2.5, individual test cases are sorted alphabetically and executed in that order. WithNUnit 2.5.1, the individual cases are not sorted, but are executed in the order in which NUnitdiscovers them. This order does not follow the lexical order of the attributes and will often varybetween different compilers or different versions of the CLR.As a result, when TestCaseAttribute appears multiple times on a method or when other data-providing attributes are used in combination with TestCaseAttribute, the order of the test casesis undefined.TestCaseSourceAttribute (NUnit 2.5)TestCaseSourceAttribute is used on a parameterized test method to identify the property,method or field that will provide the required arguments. The attribute has two publicconstructors.
    • TestCaseSourceAttribute(Type sourceType, string sourceName);TestCaseSourceAttribute(string sourceName);If sourceType is specified, it represents the class that provides the test cases. It must have adefault constructor.If sourceType is not specified, the class containing the test method is used. NUnit will constructit using either the default constructor or - if arguments are provided - the appropriate constructorfor those arguments.The sourceName argument represents the name of the source used to provide test cases. It hasthe following characteristics: It may be a field, property or method. It may be either an instance or a static member. It must return an IEnumerable or a type that implements IEnumerable. The individual items returned by the enumerator must be compatible with the signature of the method on which the attribute appears. The rules for this are described in the next section.Constructing Test CasesIn constructing tests, NUnit uses each item test case returned by the enumerator as follows: 1. If it is an object[], it is used directly to provide the arguments for the method, as in this example, which returns arguments from a named static field. 2. [Test, TestCaseSource("DivideCases")] 3. public void DivideTest(int n, int d, int q) 4. { 5. Assert.AreEqual( q, n / d ); 6. } 7. 8. static object[] DivideCases = 9. { 10. new object[] { 12, 3, 4 }, 11. new object[] { 12, 2, 6 }, 12. new object[] { 12, 4, 3 } 13. }; 14. If it is an array of some other type, NUnit can use it provided that the arguments to the method are all of that type. For example, the above code could be modified to make the three nested arrays of type int[]. 15. If it is a single value type - like numerics or DateTime - it is used directly as the sole argument to the method. The method must, of course take a single argument of the same type for this to work. This eliminates a bit of syntax on the part of the programmer, as in this example: 16. static int[] EvenNumbers = new int[] { 2, 4, 6, 8 }; 17. 18. [Test, TestCaseSource("EvenNumbers")] 19. public void TestMethod(int num) 20. { 21. Assert.IsTrue( num % 2 == 0 );
    • 22. } Note: Any user-defined struct intended to hold the arguments will be passed directly to the test method, since a struct is a value type. If you intend your user type to be used as described in the following item, you must define it as a class.23. If it is any other type of object, it is examined using reflection and any public fields or properties with the following names are used: Arguments An object[] representing the arguments to the method Categories An IList of categories to be applied to the test case. Description Sets the description property of the test ExpectedException Specifies a the Type of an exception that should be thrown by this invocation ExpectedExceptionName Specifies a the FullName of an exception that should be thrown by this invocation Properties An IDictionary of properties to be applied to the test case. Note that the values provided must be compatible with PropertiesAttribute. In particular, use of custom types or enums will cause problems. Result The expected result to be returned from the method, which must have a compatible return type. TestName Provides a name for the test. If not specified, a name is generated based on the method name and the arguments provided Ignored If true, the test case is ignored.
    • IgnoreReasonSpecifies the reason for ignoring this test case. If set to a non-empty string, then the test isignored.TestCaseData ClassAlthough any object with the required fields or properties may be used, NUnit providesthe TestCaseData class for this purpose. The following example returns TestCaseDatainstances from a data source in a separately defined class.[TestFixture]public class MyTests{ [Test,TestCaseSource(typeof(MyFactoryClass),"TestCases")] public int DivideTest(int n, int d) { return n/d; } ...}public class MyFactoryClass{ public static IEnumerable TestCases { get { yield return new TestCaseData( 12, 3 ).Returns( 4 ); yield return new TestCaseData( 12, 2 ).Returns( 6 ); yield return new TestCaseData( 12, 4 ).Returns( 3 ); yield return new TestCaseData( 0, 0 ) .Throws(typeof(DivideByZeroException)) .SetName("DivideByZero") .SetDescription("An exception is expected"); } }}This example uses the fluent interface supported by TestCaseData to make the programmore readable. The last yield statement above is equivalent to TestCaseData data = new TestCaseData(0,0); data.ExpectedException = typeof(DivideByZeroException; data.TestName = "DivideByZero"; data.Description = "An exception is expected"; yield return data;TestCaseData supports the following properties and methods, which may be appended toan instance in any order.
    • .ReturnsThe expected result to be returned from the method, which must have a compatible returntype..SetCategory(string)Applies a category to the test.SetProperty(string, string).SetProperty(string, int).SetProperty(string, double)Applies a named property and value to the test.SetDescription(string)Sets the description property of the test.SetName(string)Provides a name for the test. If not specified, a name is generated based on the method nameand the arguments provided.Throws(Type).Throws(string)Specifies a the Type or FullName of an exception that should be thrown by this invocation.Ignore()Causes the test case to be ignored..Ignore(string)Causes the test case to be ignored with a reason specified.Order of ExecutionIn NUnit 2.5, individual test cases are sorted alphabetically and executed in that order.With NUnit 2.5.1, the individual cases are not sorted, but are executed in the order inwhich NUnit discovers them. This order does not follow the lexical order of the attributesand will often vary between different compilers or different versions of the CLR.
    • As a result, when TestCaseSourceAttribute appears multiple times on a method or when other data-providing attributes are used in combination with TestCaseSourceAttribute, the order of the test cases is undefined. However, when a single TestCaseSourceAttribute is used by itself, the order of the tests follows exactly the order in which the test cases are returned from the source. Note on Object Construction NUnit locates the test cases at the time the tests are loaded, creates instances of each class with non-static sources and builds a list of tests to be executed. Each source object is only created once at this time and is destroyed after all tests are loaded. If the data source is in the test fixture itself, the object is created using the appropriate constructor for the fixture parameters provided on the TestFixtureAttribute or the default constructor if no parameters were specified. Since this object is destroyed before the tests are run, no communication is possible between these two phases - or between different runs - except through the parameters themselves.TestFixtureAttribute (NUnit 2.0 / 2.5)This is the attribute that marks a class that contains tests and, optionally, setup or teardownmethods. NUnit 2.5 introduces parameterized and generic test fixtures - see below.Most restrictions on a class that is used as a test fixture have now been eliminated. As of NUnit2.5.3, a test fixture class: May be public, protected, private or internal. May be a static class in .NET 2.0 or later. May be generic, so long as any type parameters are provided or can be inferred from the actual arguments. May not be abstract - although the attribute may be applied to an abstract class intended to serve as a base class for test fixtures. If no arguments are provided with the TestFixtureAttribute, the class must have a default constructor. If arguments are provided, they must match one of the constructors.If any of these restrictions are violated, the class is not runnable as a test and will display as anerror.It is advisable that the constructor not have any side effects, since NUnit may construct theobject multiple times in the course of a session.Beginning with NUnit 2.5, the TestFixture attribute is optional for non-parameterized, non-generic fixtures. So long as the class contains at least one method marked with the Test,TestCase or TestCaseSource attribute, it will be treated as a test fixture.
    • Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { // ... }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests ... End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { // ... };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ // ...}
    • InheritanceThe TestFixtureAttribute may be applied to a base class and is inherited by any derived classes.This includes any abstract base class, so the well-known Abstract Fixture pattern may beimplemented if desired.In order to facilitate use of generic and/or parameterized classes, where the derived class mayrequire a different number of arguments (or type arguments) from the base class, anyTestFixture attribute on a derived class causes those on the base classes to be ignored. Thisallows use of code like the following:[TestFixture]public class AbstractFixtureBase{ ...}[TestFixture(typeof(string))]public class DerivedFixture<T> : AbstractFixtureBase{ ...}Parameterized Test Fixtures (NUnit 2.5)Beginning with NUnit 2.5, test fixtures may take constructor arguments. Argument values arespecified as arguments to the TestFixture attribute. NUnit will construct a separate instance ofthe fixture for each set of arguments.Individual fixture instances in a set of parameterized fixtures may be ignored. Set the Ignorenamed parameter of the attribute to true or set IgnoreReason to a non-empty string.ExampleThe following test fixture would be instantiated by NUnit three times, passing in each set ofarguments to the appropriate constructor. Note that there are three different constructors,matching the data types provided as arguments.[TestFixture("hello", "hello", "goodbye")][TestFixture("zip", "zip")][TestFixture(42, 42, 99)]public class ParameterizedTestFixture{ private string eq1; private string eq2; private string neq; public ParameterizedTestFixture(string eq1, string eq2, string neq) { this.eq1 = eq1; this.eq2 = eq2;
    • this.neq = neq; } public ParameterizedTestFixture(string eq1, string eq2) : this(eq1, eq2, null) { } public ParameterizedTestFixture(int eq1, int eq2, int neq) { this.eq1 = eq1.ToString(); this.eq2 = eq2.ToString(); this.neq = neq.ToString(); } [Test] public void TestEquality() { Assert.AreEqual(eq1, eq2); if (eq1 != null && eq2 != null) Assert.AreEqual(eq1.GetHashCode(), eq2.GetHashCode()); } [Test] public void TestInequality() { Assert.AreNotEqual(eq1, neq); if (eq1 != null && neq != null) Assert.AreNotEqual(eq1.GetHashCode(), neq.GetHashCode()); }}Generic Test Fixtures (NUnit 2.5)Beginning with NUnit 2.5, you may also use a generic class as a test fixture. In order for NUnitto instantiate the fixture, you must either specify the types to be used as arguments toTestFixtureAttribute or use the named parameter TypeArgs= to specify them. NUnit willconstruct a separate instance of the fixture for each TestFixtureAttribute you provide.ExampleThe following test fixture would be instantiated by NUnit twice, once using an ArrayList andonce using a List<int>.[TestFixture(typeof(ArrayList))][TestFixture(typeof(List<int>))]public class IList_Tests<TList> where TList : IList, new(){ private IList list; [SetUp] public void CreateList() { this.list = new TList(); }
    • [Test] public void CanAddToList() { list.Add(1); list.Add(2); list.Add(3); Assert.AreEqual(3, list.Count); }}Generic Test Fixtures with Parameters (NUnit 2.5)If a Generic fixture, uses constructor arguments, there are three approaches to telling NUnitwhich arguments are type parameters and which are normal constructor parameters. 1. Specify both sets of parameters as arguments to the TestFixtureAttribute. Leading System.Type arguments are used as type parameters, while any remaining arguments are used to construct the instance. In the following example, this leads to some obvious duplication... 2. [TestFixture(typeof(double), typeof(int), 100.0, 42)] 3. [TestFixture(typeof(int) typeof(double), 42, 100.0)] 4. public class SpecifyBothSetsOfArgs<T1, T2> 5. { 6. T1 t1; 7. T2 t2; 8. 9. public SpecifyBothSetsOfArgs(T1 t1, T2 t2) 10. { 11. this.t1 = t1; 12. this.t2 = t2; 13. } 14. 15. [TestCase(5, 7)] 16. public void TestMyArgTypes(T1 t1, T2 t2) 17. { 18. Assert.That(t1, Is.TypeOf<T1>()); 19. Assert.That(t2, Is.TypeOf<T2>()); 20. } } 21. Specify normal parameters as arguments to TestFixtureAttribute and use the named parameter TypeArgs= to specify the type arguments. Again, for this example, the type info is duplicated, but it is at least more cleanly separated from the normal arguments... 22. [TestFixture(100.0, 42, TypeArgs=new Type[] {typeof(double), typeof(int) } )] 23. [TestFixture(42, 100.0, TypeArgs=new Type[] {typeof(int), typeof(double) } )] 24. public class SpecifyTypeArgsSeparately<T1, T2> 25. { 26. T1 t1; 27. T2 t2; 28. 29. public SpecifyTypeArgsSeparately(T1 t1, T2 t2) 30. { 31. this.t1 = t1; 32. this.t2 = t2; 33. }
    • 34. 35. [TestCase(5, 7)] 36. public void TestMyArgTypes(T1 t1, T2 t2) 37. { 38. Assert.That(t1, Is.TypeOf<T1>()); 39. Assert.That(t2, Is.TypeOf<T2>()); 40. } } 41. In some cases, when the constructor makes use of all the type parameters NUnit may simply be able to deduce them from the arguments provided. Thats the case here and the following is the preferred way to write this example... 42. [TestFixture(100.0, 42)] 43. [TestFixture(42, 100.0)] 44. public class DeduceTypeArgsFromArgs<T1, T2> 45. { 46. T1 t1; 47. T2 t2; 48. 49. public DeduceTypeArgsFromArgs(T1 t1, T2 t2) 50. { 51. this.t1 = t1; 52. this.t2 = t2; 53. } 54. 55. [TestCase(5, 7)] 56. public void TestMyArgTypes(T1 t1, T2 t2) 57. { 58. Assert.That(t1, Is.TypeOf<T1>()); 59. Assert.That(t2, Is.TypeOf<T2>()); 60. } }TestFixtureSetUpAttribute (NUnit 2.1 / 2.5)This attribute is used inside a TestFixture to provide a single set of functions that are performedonce prior to executing any of the tests in the fixture.Before NUnit 2.5, a TestFixture could have only one TestFixtureSetUp method and it wasrequired to be an instance method.Beginning with NUnit 2.5, TestFixtureSetUp methods may be either static or instance methodsand you may define more than one of them in a fixture. Normally, multiple TestFixtureSetUpmethods are only defined at different levels of an inheritance hierarchy, as explained below.If a TestFixtueSetUp method fails or throws an exception, none of the tests in the fixure areexecuted and a failure or error is reported.Example:namespace NUnit.Tests
    • { using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [TestFixtureSetUp] public void Init() { /* ... */ } [TestFixtureTearDown] public void Cleanup() { /* ... */ } [Test] public void Add() { /* ... */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <TestFixtureSetUp()> Public Sub Init() ... End Sub <TestFixtureTearDown()> Public Sub Cleanup() ... End Sub <Test()> Public Sub Add() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests { [TestFixtureSetUp] void Init(); [TestFixtureTearDown] void Cleanup(); [Test] void Add(); };}#include "cppsample.h"namespace NUnitTests { // ...}
    • package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.TestFixtureSetUp() */ public void Init() { /* ... */ } /** @attribute NUnit.Framework.TestFixtureTearDown() */ public void Cleanup() { /* ... */ } /** @attribute NUnit.Framework.Test() */ public void Add() { /* ... */ }}InheritanceThe TestFixtureSetUp attribute is inherited from any base class. Therefore, if a base class hasdefined a SetFixtureSetUp method, that method will be called after each test method in thederived class.Before NUnit 2.5, you were permitted only one TestFixtureSetUp method. If you wanted to havesome TestFixtureSetUp functionality in the base class and add more in the derived class youneeded to call the base class method yourself.With NUnit 2.5, you can achieve the same result by defining a TestFixtureSetUp method in thebase class and another in the derived class. NUnit will call base class TestFixtureSetUp methodsbefore those in the derived classes.Note: Although it is possible to define multiple TestFixtureSetUp methods in the same class, youshould rarely do so. Unlike methods defined in separate classes in the inheritance hierarchy, theorder in which they are executed is not guaranteed.TestFixtureTearDownAttribute (NUnit 2.1 / 2.5)This attribute is used inside a TestFixture to provide a single set of functions that are performedonce after all tests are completed.Before NUnit 2.5, a TestFixture could have only one SetUp method and it was required to be aninstance method.Beginning with NUnit 2.5, TestFixtureTearDown methods may be either static or instancemethods and you may define more than one of them in a fixture. Normally, multiple
    • TestFixtureTearDown methods are only defined at different levels of an inheritance hierarchy, asexplained below.So long as any TestFixtureSetUp method runs without error, the TestFixtureTearDown method isguaranteed to run. It will not run if a TestFixtureSetUp method fails or throws an exception.Example:namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] public class SuccessTests { [TestFixtureSetUp] public void Init() { /* ... */ } [TestFixtureTearDown] public void Cleanup() { /* ... */ } [Test] public void Add() { /* ... */ } }}Imports SystemImports Nunit.FrameworkNamespace Nunit.Tests <TestFixture()> Public Class SuccessTests <TestFixtureSetUp()> Public Sub Init() ... End Sub <TestFixtureTearDown()> Public Sub Cleanup() ... End Sub <Test()> Public Sub Add() ... End Sub End ClassEnd Namespace#using <Nunit.Framework.dll>using namespace System;using namespace NUnit::Framework;namespace NUnitTests{ [TestFixture] public __gc class SuccessTests {
    • [TestFixtureSetUp] void Init(); [TestFixtureTearDown] void Cleanup(); [Test] void Add(); };}#include "cppsample.h"namespace NUnitTests { // ...}package NUnit.Tests;import System.*;import NUnit.Framework.TestFixture;/** @attribute NUnit.Framework.TestFixture() */public class SuccessTests{ /** @attribute NUnit.Framework.TestFixtureSetUp() */ public void Init() { /* ... */ } /** @attribute NUnit.Framework.TestFixtureTearDown() */ public void Cleanup() { /* ... */ } /** @attribute NUnit.Framework.Test() */ public void Add() { /* ... */ }}InheritanceThe TestFixtureTearDown attribute is inherited from any base class. Therefore, if a base classhas defined a TestFixtureTearDown method, that method will be called after each test method inthe derived class.Before NUnit 2.5, you were permitted only one TestFixtureTearDown method. If you wanted tohave some TestFixtureTearDown functionality in the base class and add more in the derivedclass you needed to call the base class method yourself.With NUnit 2.5, you can achieve the same result by defining a TestFixtureTearDown method inthe base class and another in the derived class. NUnit will call base class TestFixtureTearDownmethods after those in the derived classes.Note: Although it is possible to define multiple TestFixtureTearDown methods in the same class,you should rarely do so. Unlike methods defined in separate classes in the inheritance hierarchy,the order in which they are executed is not guaranteed.
    • TheoryAttribute (NUnit 2.5) (Experimental)A Theory is a special type of test, used to verify a general statement about the system underdevelopment. Normal tests are example-based. That is, the developer supplies one or moreexamples of inputs and expected outputs either within the code of the test or - in the case ofParameterized Tests - as arguments to the test method. A theory, on the other hand, makes ageneral statement that all of its assertions will pass for all arguments satisfying certainassumptions.Theories are implemented in NUnit as methods within a TestFixture, which are annotated withthe TheoryAttribute. Theory methods must always have arguments and therefore appears quitesimilar to Parameterized Tests at first glance. However, a Theory incorporates additional datasources for its arguments and allows special processing for assumptions about that data. The keydifference, though, is that theories make general statements and are more than just a set ofexamples.Data for TheoriesThe primary source of data for a Theory is the Datapoint or Datapoints attribute. NUnit willuse any fields of the required types, which are annotated with one of these attributes, to providedata for each parameter of the Theory. NUnit assembles the values for individual argumentscombinatorially to provide test cases for the theory.In addition to the Datapoint and Datapoints attributes, it is possible to use any of the approachesfor supplying data that are recognized on normal parameterized tests. We suggest that thiscapability not be overused, since it runs counter to the distinction between a test based onexamples and a theory. However, it may be useful in order to guarantee that a specific test case isincluded.AssumptionsThe theory itself is responsible for ensuring that all data supplied meets its assumptions. It doesthis by use of the Assume.That(...) construct, which works just like Assert.That(...) but does notcause a failure. If the assumption is not satisfied for a particular test case, that case returns anInconclusive result, rather than a Success or Failure.The overall result of executing a Theory over a set of test cases is determined as follows: If the assumptions are violated for all test cases, then the Theory itself is marked as a failure. If any Assertion fails, the Theory itself fails. If at least some cases pass the stated assumptions, and there are no assertion failures or exceptions, then the Theory passes.
    • Example:In the following example, the theory SquareRootDefinition verifies that the implementation ofsquare root satisies the following definition: "Given a non-negative number, the square root of that number is always non-negative and, when multiplied by itself, gives the original number."public class SqrtTests{ [Datapoints] public double[] values = new double[] { 0.0, 1.0, -1.0, 42.0 }; [Theory] public void SquareRootDefinition(double num) { Assume.That(num >= 0.0); double sqrt = Math.Sqrt(num); Assert.That(sqrt >= 0.0); Assert.That(sqrt * sqrt, Is.EqualTo(num).Within(0.000001)); }}TimeoutAttribute (NUnit 2.5)The TimeoutAttribute is used to specify a timeout value in milliseconds for a test case. If thetest case runs longer than the time specified it is immediately cancelled and reported as a failure,with a message indicating that the timeout was exceeded.The attribute may also be specified on a fixture or assembly, in which case it indicates the defaulttimeout for any subordinate test cases.Example[Test, Timeout(2000)]public void PotentiallyLongRunningTest(){ ...}Notes 1. Beginning with NUnit 2.5.5, timeouts are suppressed when running under a debugger.
    • ValuesAttribute (NUnit 2.5)The ValuesAttribute is used to specify a set of values to be provided for an individual parameterof a parameterized test method. Since NUnit combines the data provided for each parameter intoa set of test cases, data must be provided for all parameters if it is provided for any of them.By default, NUnit creates test cases from all possible combinations of the datapoints provided onparameters - the combinatorial approach. This default may be modified by use of specificattributes on the test method itself.ExampleThe 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]public void MyTest( [Values(1,2,3)] int x, [Values("A","B")] string s){ ...}ValueSourceAttribute (NUnit 2.5)ValueSourceAttribute is used on individual parameters of a test method to identify a namedsource for the argument values to be supplied. The attribute has two public constructors.ValueSourceAttribute(Type sourceType, string sourceName);ValueSourceAttribute(string sourceName);If sourceType is specified, it represents the class that provides the data. It must have a defaultconstructor.If sourceType is not specified, the class containing the test method is used. NUnit will constructit using either the default constructor or - if arguments are provided - the appropriate constructorfor those arguments.The sourceName, represents the name of the source that will provide the arguments. It shouldhave the following characteristics: It may be a field, a non-indexed property or a method taking no arguments. It may be either an instance or a static member. It must return an IEnumerable or a type that implements IEnumerable.
    • The individual items returned from the enumerator must be compatible with the type of the parameter on which the attribute appears.Order of ExecutionIn NUnit 2.5, individual test cases are sorted alphabetically and executed in that order. WithNUnit 2.5.1, the individual cases are not sorted, but are executed in the order in which NUnitdiscovers them. This order does not follow the lexical order of the attributes and will often varybetween different compilers or different versions of the CLR.As a result, when ValueSourceAttribute appears multiple times on a parameter or when otherdata-providing attributes are used in combination with ValueSourceAttribute, the order of thearguments is undefined.However, when a single ValueSourceAttribute is used by itself, the order of the argumentsfollows exactly the order in which the data is returned from the source.Note on Object ConstructionNUnit locates the test cases at the time the tests are loaded, creates instances of each class withnon-static sources and builds a list of tests to be executed. Each source object is only createdonce at this time and is destroyed after all tests are loaded.If the data source is in the test fixture itself, the object is created using the appropriateconstructor for the fixture parameters provided on the TestFixtureAttribute, or the defaultconstructor if no parameters were specified. Since this object is destroyed before the tests arerun, no communication is possible between these two phases - or between different runs - exceptthrough the parameters themselves.Running TestsNunit provides three different runners, which may be used to load and run your tests. The console runner, nunit-console.exe, is used for batch execution. The gui runner, nunit.exe, provides interactive loading and running of tests. The pNUnit runner, pnunit-launcher.exe, is used to run parallel, distributed tests under the control of pNUnit.Third-Party RunnersVarious third-party applications are available for loading and running NUnit tests. Some of theseactually use NUnit to load the tests, while others provide their own emulation and may not workin the same way that NUnit does.
    • Because the status of such projects may change from time to time, we dont discuss themindividually here. For the latest information, consult the manufacturer of any third-party softwareor ask other users on our discussion list.Additional InformationFor additional general information on how tests are loaded and run, see Runtime Selection Assembly Isolation Configuration Files Multiple Assemblies Visual Studio SupportNUnit-ConsoleThe nunit-console.exe program is a text-based runner and can be used when you want to run allyour tests and don’t need a red/yellow/green indication of success or failure.It is useful for automation of tests and integration into other systems. It automatically saves itsresults in XML format, allowing you to produce reports or otherwise process the results. Thefollowing is a screenshot of the console program.In this example, nunit-console has just run the tests in the mock-assembly.dll that is part of theNUnit distribution. This assembly contains a number of tests, some of which are either ignored
    • or marked explicit. The summary line shows the result of the test run. Click here to see the XMLproduced for this test run.The .NET 2.0 version of the nunit-console program is built using /platform:anycpu, which causesit to be jit-compiled to 32-bit code on a 32-bit system and 64-bit code on a 64 bit system. Thiscauses an exception when NUnit is used to test a 32-bit application on a 64-bit system. To avoidthis problem, use the nunit-console-x86 program, which is built using /platform:x86, whentesting 32-bit code on a 64-bit system.NUnit-Console Command Line OptionsThe console interface has a few additional options compared to the forms interface. Thecommand line must always specify one or more file names. The console interface always createsan XML representation of the test results. This file by default is called TestResult.xml and isplaced in the working directory.Note: By default the nunit-console program is not added to your path. You must do thismanually if this is the desired behavior.Note: Under the Windows operating system, options may be prefixed by either a forward slashor a hyphen. Under Linux, a hyphen must be used. Options that take values may use an equalsign, a colon or a space to separate the option from its value.Specifying an AssemblyThe console program must always have an assembly or project specified. To run the testscontained in the nunit.tests.dll use the following command: nunit-console nunit.tests.dllTo run the tests in nunit.tests.dll through the Visual Studio project, use: nunit-console nunit.tests.csprojTo run the same tests through an NUnit test project you have defined, use: nunit-console nunit.tests.nunitSpecifying an Assembly and a Test to be RunYou may specify a test to be run by providing the full name of the test along with the containingassembly. For example to run NUnit.Tests.AssertionTests in the nunit.tests assembly use thefollowing command: nunit-console /run:NUnit.Tests.AssertionTests nunit.tests.dllThe name of the test to be run may be that of a test case, test fixture or a namespace.
    • You can specify multiple tests by separating names with commas (without spaces). For example: nunit-console/run:NUnit.Tests.AssertionTests,NUnit.Tests.ConstraintTests nunit.tests.dllUnlike the /fixture option, this option affects the running rather than the loading of the tests.Consequently it supports much broader use, including situations involving SetUpFixtures, whichare not run if the class in question is not loaded. You should use /run in lieu of /fixture in mostcases.Specifying an Assembly and a Fixture to be LoadedWhen specifying a fixture, you must give the full name of the test fixture along with thecontaining assembly. For example, to load the NUnit.Tests.AssertionTests in the nunit.tests.dllassembly use the following command: nunit-console /fixture:NUnit.Tests.AssertionTests nunit.tests.dllThe name specified after the /fixture option may be that of a TestFixture class, a legacy suite(using the Suite property ) or a namespace. If a namespace is given, then all fixtures under thatnamespace are loaded.This option is provided for backward compatibility. In most cases, you will be better served byusing the /run option.Specifying the .NET Framework VersionMost applications are written to run under a specific version of the CLR. A few are designed tooperate correctly under multiple versions. In either case, it is important to be able to specify theCLR version to be used for testing.Prior to version 2.5, it was necessary to run the console program itself using the CLR versionunder which you wanted to run tests. This was done either by editing the nunit-console.exe.config file or by setting the COMPLUS_Version environment variable beforerunning the program.Under NUnit 2.5 and later versions, you may still use either of these approaches, but a simplermethod is available.The /framework option allows you to specify the version of the runtime to be used in executingtests. If that version specified is different from the one being used by NUnit, the tests are run in aseparate process. For example, you may enter nunit-console myassembly.dll /framework:net-1.1
    • This command will run tests under .NET 1.1 even if you are running the .NET 2.0 build of thenunit-console. Beginning with version 2.5.3, all versions of .NET through 4.0 as well as Monoprofiles 1.0, 2.0 and 3.5 are supported.Specifying Test Categories to Include or ExcludeNUnit provides CategoryAttribute for use in marking tests as belonging to one or morecategories. Categories may be included or excluded in a test run using the /include and /excludeoptions. The following command runs only the tests in the BaseLine category: nunit-console myassembly.dll /include:BaseLineThe following command runs all tests except those in the Database category: nunit-console myassembly.dll /exclude:DatabaseMultiple categories may be specified on either option, by using commas to separate them.Notes: Beginning with NUnit 2.4, the /include and /exclude options may be combined on thecommand line. When both are used, all tests with the included categories are run except for thosewith the excluded categories.Beginning with NUnit 2.4.6, you may use a Category Expression with either of these options:A|B|C Selects tests having any of the categories A, B or C.A,B,C Selects tests having any of the categories A, B or C.A+B+C Selects only tests having all three of the categories assignedA+B|C Selects tests with both A and B OR with category C.A+B-C Selects tests with both A and B but not C.-A Selects tests not having category A assignedA+(B|C)
    • Selects tests having both category A and either of B or CThe comma operator is equivalent to | but has a higher precendence. Order of evaluation is asfollows: 1. Unary exclusion operator (-) 2. High-precendence union operator (,) 3. Intersection and set subtraction operators (+ and binary -) 4. Low-precedence union operator (|)Note: Because the operator characters have special meaning, you should avoid creating acategory that uses any of them in its name. For example, the category "db-tests" could not beused on the command line, since it appears to means "run category db, except for category tests."The same limitation applies to characters that have special meaning for the shell you are using.For a clear understanding of how category selection works, review the documentation for boththe Category Attribute and the Explicit Attribute.Redirecting OutputOutput created by the test, which is normally shown on the console, may be redirected to a file.The following command redirects standard output to the file TestResult.txt: nunit-console nunit.tests.dll /out:TestResult.txtThe following command redirects standard error output to the StdErr.txt file. nunit-console nunit.tests.dll /err:StdErr.txtNote:This option only redirects output produced by the tests, together with selected NUnitoutput that is interspersed with the test output. It does not redirect all console output. If you wantto redirect all output to a file, you should use command line redirection as supported by the shellyou are using. This option exists for the purpose of separating test output from other output, suchas the NUnit summary report.Labeling Test OutputThe output from each test normally follows right after that of the preceding test. You may use the/labels option to cause an identifying label to be displayed at the start of each test case.Specifying the XML file nameAs stated above, the console program always creates an XML representation of the test results.To change the name of the output file to "console-test.xml" use the following command lineoption: nunit-console /xml:console-test.xml nunit.tests.dll
    • Note: For additional information see the XML schema for the test results. This file is in the samedirectory as the executable and is called Results.xsd.Specifying which Configuration to runWhen running tests from a Visual Studio or NUnit project, the first configuration found will beloaded by default. Usually this is Debug. The configuration loaded may be controlled by usingthe /config switch. The following will load and run tests for the Release configuration ofnunit.tests.dll. nunit-console nunit.tests.csproj /config:ReleaseNote: This option has no effect when loading an assembly directly.Specifying Multiple AssembliesYou may run tests from multiple assemblies in one run using the console interface even if youhave not defined an NUnit test project file. The following command would run a suite of testscontained in assembly1.dll, assembly2.dll and assembly3.dll. nunit-console assembly1.dll assembly2.dll assembly3.dllNotes: You may specify multiple assemblies, but not multiple NUnit or Visual Studio projectson the command line. Further, you may not specify an NUnit or Visual Studio project togetherwith a list of assemblies.Beginning with NUnit 2.4, the console loads multiple assemblies specified in this way intoseparate AppDomains by default. You may provide a separate config file for each assembly. Youmay override the default by use of the /domain option.Beginning with NUnit 2.4, the /fixture option, when used with multiple assemblies, will run testsmatching the fixture name in all the assemblies. In earlier versions, only the first test found wasexecuted.Controlling the Use of ProcessesThe /process option controls how NUnit loads tests in processes. The following values arerecognized. Single All the tests are run in the nunit-console process. This is the default. Separate A separate process is created to run the tests.
    • Multiple A separate process is created for each test assembly, whether specified on the command line or listed in an NUnit project file.Controlling the Use of AppDomainsThe /domain option controls of the creation of AppDomains for running tests. The followingvalues are recognized: None No domain is created - the tests are run in the primary domain. This normally requires copying the NUnit assemblies into the same directory as your tests. Single A test domain is created - this is how NUnit worked prior to version 2.4 Multiple A separate test domain is created for each assemblyThe default is to use multiple domains if multiple assemblies are listed on the command line.Otherwise a single domain is used.Specifying a Default Timeout ValueThe /timeout option takes an int value representing the default timeout to be used for test casesin this run. If any test exceeds the timeout value, it is cancelled and reported as an error. Thedefault value may be overridden for selected tests by use of TimeoutAttribute.Note: If you do not use this option, no timeout is set and tests may run for any amount of time.Other OptionsThe /noshadow option disables shadow copying of the assembly in order to provide improvedperformance.The /nothread option suppresses use of a separate thread for running the tests and uses the mainthread instead.The /wait option causes the program to wait for user input before exiting. This is useful whenrunning nunit-console from a shortcut.The /xmlconsole option displays raw XML output on the console rather than transforming it.This is useful when debugging problems with the XML format.
    • The /nologo option disables display of the copyright information at the start of the program.The /help or /? option displays a brief help messageNUnit Gui RunnerThe nunit.exe program is a graphical runner. It shows the tests in an explorer-like browserwindow and provides a visual indication of the success or failure of the tests. It allows you toselectively run single tests or suites and reloads automatically as you modify and re-compile yourcode. The following is a screenshot of NUnit running the same mock-assembly.dll shown in thenunit-console example.Tree DisplayThis version of NUnit uses symbols in the test tree, which allow those who are unable to easilydistinguish colors to determine the test status. Successful tests are colored green, with a checkmark. Tests that are ignored are marked with a yellow circle, containing a question mark. If anytests had failed, they would be marked red, with an X symbol.
    • In this example, there were a total of 11 test cases, but one of them was not counted because itwas marked Explicit. Note that it is shown as a gray circle in the tree. Of the remaining 10 tests,5 were run successfully and 5 were ignored.The symbols shown in the tree are actually files in the NUnit bin directory. These files are namedSuccess.jpg, Failure.jpg and Ignored.jpg and may be modified or replaced by the user.Progress BarThe progress bar shows the progress of the test. It is colored according to the "worst" resultobtained: red if there were any failures, yellow if some tests were ignored and green for success.Result TabsThe tabs along the bottom of the display show the results of running a test. The Errors andFailures tab displays the error message and stack trace for both unexpected exceptions andassertion failures. Beginning with NUnit 2.5, source code for each stack location can bedisplayed in this tab - as is seen above - provided that the program was compiled with debuginformation.The Tests Not Run tab provides a list of all tests that were selected for running but were not run,together with the reason.The Text Output tab displays text output from the tests, potentially including console output,trace output and log output. The default display provides a single tab, but additional tabs may becreated by the user to hold specific kinds of output. For more information on creating new tabs,see the documentation for the Settings Dialog.Mini-GuiSince the release of NUnit 2.4, an alternate "mini-gui" is also available. It may be selected fromthe View menu. In the following screenshot, the mini gui window has been positioned next to theVisual Studio IDE so that both windows can be seen.
    • NUnit Command Line OptionsThe forms interface may be run with or without the name of a file containing tests on thecommand line. If the program is started without any file specified, it automatically loads themost recently loaded assembly.Note: Options that take values may use an equal sign, a colon or a space to separate the optionfrom its value.Note: Under the Windows operating system, options may be prefixed by either a forward slashor a hyphen. Under Linux, a hyphen must be used. Options that take values may use an equalsign, a colon or a space to separate the option from its value.
    • Run without loading an AssemblyTo suppress loading of the most recent assembly, use the /noload switch: nunit /noloadSpecifying an AssemblyThe other option is to specify an assembly or project file name on the command line. Thefollowing will start the forms interface with the assembly nunit.tests.dll: nunit nunit.tests.dllThe following will start the forms interface loading the same assembly through its Visual Studioproject definition: nunit nunit.tests.csprojAssuming an NUnit test project has been created containing the assembly, the following willagain load nunit.tests.dll: nunit nunit.tests.nunitSpecifying an Assembly and a FixtureWhen specifying a a fixture, you must give the full name of the test fixture along with thecontaining assembly. For example, to load only the NUnit.Tests.AssertionTests in thenunit.tests.dll assembly use the following command: nunit /fixture:NUnit.Tests.AssertionTests nunit.tests.dllThe name specified after the /fixture option may be that of a TestFixture class, or a namespace.If a namespace is given, then all fixtures under that namespace are loaded. This option may beused with Visual Studio or NUnit projects as well.Specifying Test Categories to Include or ExcludeNUnit provides CategoryAttribute for use in marking tests as belonging to one or morecategories. Categories may be included or excluded in a test run using the /include or /excludeoptions. The following command starts the gui with only the tests in the BaseLine categoryselected: nunit myassembly.dll /include:BaseLineThe following command selects all tests except those in the Database category: nunit myassembly.dll /exclude:Database
    • Multiple categories may be specified on either option, by using commas to separate them.Note: At this time, the /include and /exclude options may not be combined on the command line.Load and Run All TestsNormally, nunit only loads an assembly and then waits for the user to click on the Run button. If youwish to have the tests run immediately, use the /run option: nunit nunit.tests.dll /runLoad and Run Selected TestsTo load and immediately rerun the last selected tests, use the /runselected option: nunit nunit.tests.dll /runselectedNote: If no selection has been saved, this option works just like /run.Specifying which Configuration to LoadWhen loading a Visual Studio project or an NUnit project, the first configuration found will beloaded by default. Usually this is Debug. The configuration loaded may be controlled using the/config switch. The following will load the Release configuration of the nunit.tests.dll: nunit nunit.tests.csproj /config:ReleaseNote: This option has no effect when loading an assembly directly.Specifying Multiple AssembliesThe forms interface does not currently provide for specifying more than one assembly on thecommand line. Multiple-assembly projects must be loaded by specifying the name of a VisualStudio solution file or an NUnit test project.Clearing the ShadowCopy CacheThe /cleanup option erases the shadow copy cache and exits.Displaying HelpThe /help or /? option displays a message box containing a brief help message.Main Menu
    • File MenuNew Project…Closes any open project, prompting the user to save it if it has been changed and then opens aFileSave dialog to allow selecting the name and location of the new project.Open Project…Closes any open project, prompting the user to save it if it has been changed and then opens aFileOpen dialog to allow selecting the name and location of an assembly, a test project or (ifVisual Studio support is enabled) a Visual Studio project.CloseCloses any open project, prompting the user to save it if it has been changed.SaveSaves the currently open project. Opens the Save As dialog if this is the first time the project isbeing saved.Save As…Opens a FileSave dialog to allow specifying the name and location to which the project shouldbe saved.Reload ProjectCompletely reloads the current project by closing and re-opening it.Reload TestsReloads the tests, merging any changes into the tree.Select RuntimeDisplays a list of runtime versions you may select in order to reload the tests using that runtime.This submenu is only present if you have more than one runtime version available. Anyframework versions not supported by your NUnit installation will be disabled until you installthe necessary NUnit components.Recent Files…Displays a list of recently opened files from which the user is able to select one for opening.
    • ExitCloses and exits the application. If a test is running, the user is given the opportunity to cancel itand or to allow it to continue. If the open project has any pending changes, the user is given theopportunity to save it.View MenuFull GuiDisplays the complete gui - as in prior versions of NUnit. This includes the errors and failuresand other tabs and the progress bar.Mini GuiSwitches the display to the mini-gui, which consists of the tree display only.Result TabsDisplays a submenu that allows showing or hiding the tabs on the right hand side of the display.Errors & Failures, Tests Not Run, etc.Selects the individual tabs to display.TreeDisplays the Tree submenu.Show CheckboxesTurns the display of checkboxes in the tree on or off. The checkboxes may be used to selectmultiple tests for running.ExpandExpands the currently selected tree node.CollapseCollapses the currently selected tree node.
    • Expand AllExpands all nodes of the tree.Collapse AllCollapses all nodes in the tree to the root.Hide TestsCollapses all fixture nodes, hiding the test cases.Properties…Displays the Properties Dialog for the currently selected test.GUI FontDisplays a submenu that allows changing the general font used by NUnit.IncreaseIncreases the size of the font.DecreaseDecreases the size of the font.Change...Displays the Font Change dialog.RestoreRestores the default font.Fixed FontDisplays a submenu that allows changing the fixed font used to display console output from thetests.IncreaseIncreases the size of the fixed font.
    • DecreaseDecreases the size of the fixed font.RestoreRestores the default fixed font.Assembly Details...Displays information about loaded test assemblies.Status BarDisplays or hides the status bar.Project MenuConfigurationsDisplays a submenu allowing selecting, adding or editing a configuration.Debug, Release, etc.Loads the specified configuration for testing.Add…Opens the Add Configuration Dialog, which allows entry of the name of the new configurationand specifying an existing configuration to use as a template.Edit…Opens the Configuration Editor.Add Assembly…Displays a FileOpen dialog to allow selecting an assembly to be added to the activeconfiguration of the currently open project.
    • Add VS Project…Only available if Visual Studio Support is enabled. Displays a FileOpen dialog to allowsselecting a Visual Studio project to be added to the currently open project. Entries are added foreach configuration specified in the VS project, creating new configurations in the test project ifnecessary.Edit…Opens the Project Editor.Test MenuRun AllRuns all the tests.Run SelectedRuns the test or tests that are selected in the tree. If checkboxes are visible, any checked tests arerun by preference. This is the same function provided by the Run button.Run FailedRuns only the tests that failed on the previous run.Stop RunStops the test run. This is the same function provided by the Stop button.Tools MenuSave Results as XML…Opens a FileSave Dialog for saving the test results as an XML file.Exception Details…Displays detailed information about the last exception.
    • Options...Displays the Options Dialog.Addins...Displays the Addins Dialog.Help MenuNUnit HelpDisplays the NUnit documentation, if installed. Otherwise, attempts to connect to the NUnit website.About NUnit…Displays info about your version of NUnit and a link to the nunit.org site.Context MenuThe context menu is displayed when one of the tree nodes is right-clicked.RunRuns the selected test - disabled if a test is running.Run AllRuns all the tests.Run FailedRuns only the tests that failed on the previous run.Show CheckboxesTurns the display of checkboxes in the tree on or off. The checkboxes may be used to selectmultiple tests for running.
    • ExpandExpands the selected test node – invisible if the node is expanded or has no children.CollapseCollapses the selected test node – invisible if the node is collapsed or has no children.Expand AllExpands all nodes of the tree.Collapse AllCollapses all nodes in the tree to the root.Load FixtureReloads only the currently selected fixture or namespace. The fixture, once loaded, remains ineffect through any subsequent reloads. This generally results in substantial reduction in loadtime.Clear FixtureReloads all the tests, clearing the currently loaded fixture.PropertiesDisplays the Test Properties for the selected test node.Settings DialogThe Settings Dialog is displayed using the Tools | Settings menu item and allows the user tocontrol some aspects of NUnit’s operation. Beginning with NUnit 2.4.4, a tree-based dialogreplaced the older tabbed format.Gui Settings - General
    • Gui DisplayFull GuiDisplays the complete gui - as in prior versions of NUnit. This includes the test result tabs andthe progress bar.Mini GuiSwitches the display to the mini-gui, which consists of the tree display only.Recent FilesThe Display ... files in list TextBox allows the user to choose the number of entries to display inthe recent files list.Normally, NUnit checks that project files still exist before displaying them in the recent files list.This can cause long delays if the file is on a network connection that is no longer available.Unchecking Check that files exist before listing will avoid this delay, so long as the missingfile is not actually selected.If Load most recent project at startup is checked, the GUI will load the last file opened unlessit is run with a specific filename or with the /noload parameter.Gui Settings - Tree Display
    • Tree ViewThe list box allows selecting the degree of expansion of the tree when tests are loaded:Auto – selects a setting based on the space available for the tree display.Expand – expands all testsCollapse – collapses all testsHide Tests – expands all suites except for the fixtures themselves.If Clear results when reloading is checked, an automatic or manual reload will reinitialize alltest nodes in the tree (grey display) – if it is not checked, result information for tests that do notseem to have changed will be retained.If Save visual state of each project is checked, NUnit saves the state of the tree and restores itwhen the project is next opened. The information saved includes which branches of the tree areexpanded, the selected node, any checked nodes and any category selection.If Show Checkboxes is checked, the tree includes checkboxes, which may be used to selectmultiple tests for running. This setting is also available in the View | Tree menu.
    • Test StructureIf Automatic Namespace suites is selected, tests will be shown in a hierarchical listing based onnamespaces. This is the standard display as used in versions prior to NUnit 2.4.If Flat list of TestFixtures is selected, tests will be shown as a sequential list of fixtures.Gui Settings - Test ResultsErrors TabCheck Display Errors and Failures Tab to display the Errors and Failures tab, which showsinformation about failing tests.Check Enable Failure ToolTips to display the tip window over the Errors and Failures displayand the stack trace. Clear it if you prefer not to see the tip window.Check Enable Word Wrap to turn on word wrapping in the Errors and Failures display. Whileyou can select this item and the preceding one at the same time, they do not interact well, so youwill normally choose one or the other.Not Run TabCheck Display Tests Not Run Tab to display the Tests Not Run tab, which shows informationabout tests that were skipped or ignored.Gui Settings - Text Output
    • Select TabThe Select Tab dropdown list is used to select one of the output tabs, for which settings are to beviewed or changed. It also contains entries that allow you to add a new tab or edit the list of tabs.The Restore Defaults button is used to restore the default setting, which is a single tab labeled"Text Output." The default tab displays all types of output and includes a label for each test thatdisplays text.The Title text box is used to modify the title displayed for the selected output tab.Enabled is checked by default. If you uncheck it, the selected tab will be removed from the tabcontrol. This allows you to temporarily suppress output to a tab without actually removing itsdefinition.ContentThe four check boxes enable or disable a particular type of output on the selected outputwindow. For each type, the display captures output produced while your test is running - eitherby the test itself or by the program you are testing.Standard OutputCaptures all output written to Console.Out.
    • Error OutputCaptures all output written to Console.Error.Trace OutputCaptures all output written to Trace or Debug.Log OutputCaptures output written to a log4net log. NUnit captures all output at the Error level or aboveunless another level is specified for the DefaultLogThreshold setting in the configuration file forthe test assembly or project.Test LabelsCheck Display TestCase Labels to precede text in the output window with the name of the testthat produced it.Check Suppress label if no output is displayed to eliminate display of labels for tests thatproduce no output in the window.Test Loader Settings - Assembly Isolation
    • Default Process ModelThese settings determine NUnits default use of operating system processes and may beoverridden by settings in the NUnit project.If Run tests directly in the NUnit process is selected, all tests are run in a test domain in thesame process as NUnit. This is the way previous versions of NUnit ran tests and is the defaultsetting.If Run tests in a single separate process is selected, a separate process is used for all tests.If Run tests in a separate process per Assembly is selected, a separate process is used for eachtest assembly.Default Domain UsageIf Use a separate AppDomain per Assembly is selected, each assembly in a multiple-assemblytest run will be loaded in a separate AppDomain. This setting is not available when Run tests ina separate process per Assembly is selected above.If Use a single AppDomain for all tests is selected, all assemblies in a multiple-assembly testrun will use the same AppDomain. This was the standard behavior of NUnit prior to version 2.4and is the default setting.
    • If Merge tests across assemblies is checked, the display of tests will not be divided acrossassemblies. If automatic namespace suites are used, they will be merged across all assemblies.This option is only available when tests are run in the same appdomain.Test Loader Settings - Assembly ReloadAssembly ReloadIf Reload before each test run is checked, a reload will occur whenever the run button ispressed whether the assemblies appear to have changed or not.If Reload when test assembly changes is checked, assemblies are watched for any change andan automatic reload is initiated. This item is disabled on Windows 98 or ME.If Re-run last tests run is checked, tests are re-run whenever a Reload takes place.Test Loader Settings - Advanced
    • Shadow CopyNUnit normally uses .Net shadow-copying in order to allow you to edit and recompileassemblies while it is running. Uncheck this box to disable shadow-copy only if you have aparticular problem that requires it.Note: If you are tempted to disable shadow copy in order to access files in the same directory asyour assembly, you should be aware that there are alternatives. Consider using theAssembly.Codebase property rather than Assembly.Location.IDE Support Settings - Visual Studio
    • Visual StudioIf Enable Visual Studio Support is checked, the user will be able to open Visual Studioprojects and solutions and add Visual Studio projects to existing test projects.Addins DialogThe Addins Dialog is displayed using the Tools | Addins menu item on the main menu. It lists alladdins that have been found and loaded by NUnit.AddinThis column lists the name of the addin, as defined by its author.StatusThis column shows the status of each addin. Possible values are Unknown Enabled Disabled
    • Loaded ErrorDescriptionIf the author of an addin has provided a description, it is shown here when the addin is selected.MessageIf the addin failed to load, its status will be shown as Error and any error message displayed herewhen that addin is selected.Test Properties DialogThe test properties dialog is displayed using either the View | Properties menu item on the mainmenu or the Properties item on the context menu. It shows information about the test and – if ithas been run – about the results. The dialog contains a “pin” button in the upper right corner,which causes it to remain open as the user clicks on different tests.
    • Configuration EditorThe Configuration Editor is displayed using the Project | Configuration | Edit… menu item andsupports the following operations:
    • RemoveRemove the selected configuration. If it was the active config, then the next one in the list ismade active.RenameRename the selected configuration.Add…Add a new configuration. The Add Configuration dialog allows specifying an existingconfiguration to use as a template.Make ActiveMakes the selected configuration active.CloseExits the configuration editorProject EditorThe Project Editor is displayed through the Project | Edit menu item and allows creating ormodifying NUnit test projects. It should be noted that a Test Project is active whenever any testshave been loaded, even if no project was explicitly created or referenced. In the case of anassembly being loaded, an internal wrapper project is created. This allows the user to change
    • settings and save the project directly without needing to perform any extra steps. The editorconsists of a common area and two tabs, as seen in the image below.Common AreaThe common area of the Project Editor contains information pertaining to the project as a whole.Information that applies to a particular configuration is displayed in the General and Assembliestabs.Project PathThis label shows the full path to the project file. In the case of a wrapper project, the path is setto the same directory as the assembly that was initially opened.Application BaseThis TextBox allows the user to change the project AppBase, which defaults to the directory ofthe project file. The button to the right of the TextBox allows the user to browse and select adirectory.Process ModelThis dropdown list allows you to specify how operating system processes are used in loading andrunning the tests in this project. Four settings are defined: The Default setting refers to the option selected by the user on the Assembly Isolation page of the NUnit Settings Dialog. Single means that tests are run in a test domain in the same process as NUnit. This is the way previous versions of NUnit ran tests. Separate means that all the tests are run in a separate process that NUnit creates. Multiple means that NUnit will create a separate process for each test assembly in the project and run its tests there.Domain UsageThis dropdown list allows you to specify how tests are loaded into AppDomains by NUnit. Threesettings are defined: The Default setting refers to the option selected by the user on the Assembly Isolation page of the NUnit Settings Dialog. Single means that all tests will run in a single test domain created by NUnit. This was the way versions of NUnit prior to 2.4 ran tests. Multiple means that each test assembly is loaded into a separate AppDomain. This setting is not available when Multiple processes are selected in the Process Model dropown.
    • ConfigurationThis dropdown list allows you to select the particular configuration within a project that isdisplayed in the bottom part of the dialog.Edit Configs...This button opens the Configuration Editor, which allows you to add, delete or rename configsand set the active configuration.General TabThe General tab allows setting a number of options pertaining to the selected configuration, all ofwhich will be stored in the NUnit project file as attributes of the xml node.
    • RuntimeThis dropdown allows you to select a particular runtime framework to be used for loading andrunning tests under the current configuration. Currently, only Microsoft .NET and Mono aresupported. If Any is selected, the tests will be run under the same runtime that NUnit itself iscurrently using.VersionThis ComboBox allows you to select the particular version of the runtime framework to be usedfor loading and running tests under the current configuration. The dropdown list contains entriesfor Default 1.0 1.1 2.0 4.0If you select "Default" the assemblies in the project are examined to determine the version that isrequired. See Runtime Selection for more information on how NUnit selects the version to beused.In special cases, you may wish to enter a version number that is not listed in the list box. Youmay specify the version using two, three or four components. The version you provide will besaved as you enter it. Leaving the text box blank is equivalent to selecting "Default."Note: Running tests under a different runtime or version from the one that NUnit is currentlyusing will force them to run in a separate process.Note: To conform with normal usage, specifying Mono as the runtime with "1.0" as the versionresults in use of the Mono 1.0 profile, equating to version 1.1.4322.ApplicationBaseThe ApplicationBase defaults to the directory containing the project file. Beginning with NUnit2.2.3, it may be set to any location that is desired.Configuration File NameThe configuration file defaults to the name of the test project with the extension changed from.nunit to .config. The user may substitute another name.
    • PrivateBinPathBy default, the PrivateBinPath is generated from the assembly locations specified on theAssemblies Tab. For those applications requiring a different level of control, it may be specifiedmanually or using this editor or placed in the configuration file.Assemblies TabThe assemblies tab contains the list of assemblies that form part of this test project.Note: Although the dialog shows the location of assemblies as absolute paths, they are alwayspersisted in the NUnit project file as paths relative to the application base. This allows movingprojects as a whole to a different directory location.
    • Add...Opens a dialog allowing adding an assembly to this configuration. If Visual Stuio support isenabled, you may also select and add a VS project.RemoveAfter confirmation, removes the selected assembly from this configuration.Assembly PathThis text box displays the full path to the selected assembly. You may edit the contents to changethe path to the assembly.PNUnitPNUnit stands for "Parallel NUnit." It is an extension of NUNit developed by Pablo SantosLuaces and his team at Codice Software for their internal use in testing the Plastic (TM)Software Configuration Management System. Codice released PNUnit to the community in2007.As part of the NUnit 2.5 release, we worked with the NUnit and PNUnit teams worked togetherto make PNUnit work with NUnit without any modifications. PNUnit is now included in theNUnit distribution.How it WorksPNUnit is not intended for "casual" parallelism merely to make the tests run faster. Rather, itsintended as a way to test applications composed of distributed, communicating components.Tests of each component run in parallel and use memory barriers to synchronize their operation.PNUnit uses a special executable to launch its tests. The launcher reads an xml file that specifiesthe tests to be executed and where they should run, whether on the same machine or on anothermachine on the network.For more information about using PNUnit, consult the documentation atwww.codicesoftware.comFuture PlansPNUnit will be integrated with NUnit so that parallel, distributed tests may be used through thenormal NUnit console or gui runners.
    • Runtime SelectionBefore loading an assembly, NUnit must determine what runtime to use. By default (see belowfor exceptions) the following rules are used: 1. If the assembly was built for the same runtime under which NUnit is currently running, then that runtime is used. 2. If the assembly was built for a different runtime version and that version is available, NUnit uses it, running out of process if necessary. 3. If the assembly was built for a different runtime version, which is not available, then the result depends on whether the build version is earlier or later than the current version. If earlier, the test will be run using the same runtime version under which NUnit is running. If later, then it is not possible to load the test and NUnit gives an error message. 4. If multiple assemblies are being run at the same time, NUnit first determines the runtime under which each assembly was built. The highest version is then selected for the entire group, and rules 1 through 3 are applied.Note: For versions 2.5.4 and 2.5.5, automatic runtime selection only works in the Gui runner.Use the /framework option to select the appropriate runtime under the Console runner.Overriding the DefaultsThe default runtime framework may be overridden using command line arguments, menu itemsin the Gui or settings in an NUnit project file. Provided that the requested framework isavailable, it will be used. If it isnt available, NUnit will issue an error message.Note: To use version 1.x runtimes, you must have NUnits support for those runtimes installed,in addition to the runtime itself. This support is an option of the NUnit installation.Command Line OptionsThe /framework option of console runner allows you to specify the framework type and versionto be used for a test run. See NUnit-Console Command Line Options for more information.Gui Menu SelectionThe main menu provides File | Select Runtime sub-items allowing you to reload the tests undera specific runtime. See Main Menu for more info.Project SettingsThe NUnit project format supports specification of a specific runtime to be used with a project atthe configuration level. See Project Editor for more information.
    • Assembly IsolationNUnit isolates test assemblies from its own code and from one another by use of separateAppDomains and/or Processes.By default, NUnit loads a test assembly into a separate AppDomain, while its own code runs inthe primary AppDomain.When multiple assemblies are run at the same time, NUnit loads them differently depending onhow they were specified. For assemblies that are part of an NUnit project, then a singleAppDomain is used. If the assemblies were specified on the console runner command line, thena separate AppDomain is used for each of them.If greater separation is desired, test assemblies may be loaded into a separate Process or intomultiple processes. This is done automatically by NUnit in the case where the tests are to be rununder a different runtime from the one that NUnit is currently using.Controlling IsolationBeyond the NUnit default behavior, the user may control the level of isolation through thecommand line or through NUnits general settings. Process and AppDomain isolation may alsobe specified as part of the settings of an NUnit project.Command LineAssembly Isolation may be specified on the console runner commandline using the /process and/domain options. See NUnit-Console Command Line Options for more information.General SettingsThe built-in NUnit defaults may be overridden using the Assembly Isolation panel of the NUnitSettings Dialog. Settings made here are saved and become the new default values for allexecutions of NUnit until changed. For more info, see the Settings Dialog page.Project SettingsIsolation settings may be specified for an individual NUnit project using the Project Editor.Configuration FilesNUnit uses configuration files for the test runner executable – either nunit-console.exe ornunitgui.exe – as well as for the tests being run. Only settings that pertain to NUnit itself shouldbe in the nunit-console.exe.config and nunit-gui.exe.config, while those that pertain to your ownapplication and tests should be in a separate configuration file.
    • NUnit Configuration FilesOne main purpose of the nunit-console and nunit-gui config files is to allow NUnit to run withvarious versions of the .NET framework. NUnit is built using versions 1.1 and 2.0 of theframework. The two builds are provided as separate downloads and either build can be made torun against other versions of the CLR.As delivered, the section of each config file is commented out, causing NUnit to run with theversion of .NET used to build it. If you uncomment the section, the entries there control the orderin which alternate framework versions are selected.Test Configuration FileWhen a configuration file is used to provide settings or to control the environment in which a testis run, specific naming conventions must be followed.If a single assembly is being loaded, then the configuration file is given the name of the assemblyfile with the config extension. For example, the configuration file used to run nunit.tests.dll mustbe named nunit.tests.dll.config and located in the same directory as the dll.If an NUnit project is being loaded into a single AppDomain, the configuration file uses thename of the project file with the extension changed to config. For example, the projectAllTests.nunit would require a configuration file named AllTests.config, located in the samedirectory as AllTests.nunit. The same rule is followed when loading Visual Studio projects orsolutions.Note: The above only applies if a single AppDomain is being used. If an NUnit project is loadedusing a separate AppDomain for each assembly, then the individual configuration files for eachof the assemblies are used.Generally, you should be able to simply copy your application config file and rename it asdescribed above.It is also possible to effect the behavior of NUnit by adding special sections to the test configfile. A config file using these sections might look like this:<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <sectionGroup name="NUnit"> <section name="TestCaseBuilder" type="System.Configuration.NameValueSectionHandler"/> <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/> </sectionGroup> </configSections> <NUnit>
    • <TestCaseBuilder> <add key="OldStyleTestCases" value="false" /> </TestCaseBuilder> <TestRunner> <add key="ApartmentState" value="MTA" /> <add key="ThreadPriority" value="Normal" /> <add key="DefaultLogThreshold" value="Error" /> </TestRunner> </NUnit> ...</configuration>The entries in the above file are all set to default values. The meaning of each setting is asfollows:OldStyleTestCasesIf set to "true" NUnit will recognize methods beginning "test..." as tests. The prefix is caseinsensitive.ApartmentStateSets the apartment state for the thread used to run tests.ThreadPrioritySets the thread priority for the test thread.DefaultLogThresholdSets the level for logging captured by NUnit. In the current version only log4net logging iscaptured, so the level must be one that is defined by log4net.Multiple-Assembly SupportSince version 2.1, NUnit has allowed loading suites of tests from multiple assemblies in both theconsole and GUI runners. This may be done on an adhoc basis or by creating NUnit test projectssaved as files of type .nunit. In either case, a top-level suite is constructed, which contains theroot suite for each assembly. Tests are run and reported just as for a single assembly.Adhoc UsageUsing the console runner, multiple assemblies may be run simply by specifying their names onthe command line. See NUnit-Console Command Line Options for an example of this usage.
    • The gui runner does not support specifying multiple assemblies on the command-line. However,you can load a single assembly and then use the Project menu to add additional assemblies.Additionally, you can drag multiple assemblies to the tree view pane, in which case they willreplace any assemblies already loaded.NUnit Test ProjectsRunning tests from multiple assemblies is facilitated by the use of NUnit test projects. These arefiles with the extension .nunit containing information about the assemblies to be loaded. Thefollowing is an example of a hypothetical test project file:<NUnitProject> <Settings activeconfig="Debug"/> <Config name="Debug"> <assembly path="LibraryCorebinDebugLibrary.dll"/> <assembly path="LibraryUIbinDebugLibraryUI.dll"/> </Config> <Config name="Release"> <assembly path="LibraryCorebinReleaseLibrary.dll"/> <assembly path="LibraryUIbinReleaseLibraryUI.dll"/> </Config></NUnitProject>This project contains two configurations, each of which contains two assemblies. The Debugconfiguration is currently active. By default, the assemblies will be loaded using the directorycontaining this file as the ApplicationBase. The PrivateBinPath will be set automatically toLibraryCorebinDebug;LibraryUIbinDebug or to the corresonding release path. XMLattributes are used to specify non-default values for the ApplicationBase, Configuration File andPrivateBinPath. The Project Editor may be used to create or modify NUnit projects.Even when you are running a single test assembly, NUnit creates an internal project to containthat assembly. If you are using the gui, you can save this project, edit it, add additionalassemblies, etc. Note that the gui does not display the internal project unless you add assembliesor modify it in some other way.If you use Visual Studio Support to load Visual Studio .Net project or solution files, NUnitconverts them to Test projects internally. As with other internal projects, these test projects arenot saved automatically but may be saved by use of the File menu.Loading and RunningIn the past, test writers have been able to rely on the current directory being set to the directorycontaining the single loaded assembly. For the purpose of compatibility, NUnit continues to setthe current directory to the directory containing each assembly whenever any test from thatassembly is run.Additionally, because some assemblies may rely on unmanaged dlls in the same directory, thecurrent directory is also set to that of the assembly at the time the assembly is loaded. However,
    • in cases where multiple assemblies reference the same unmanaged assembly, this may not besufficient and the user may need to place the directory containing the unmanaged dll on the path.Visual Studio SupportVisual Studio support in this release is a sort of “poor man’s integration.” We have implementeda number of features while avoiding any that would require using an Addin or otherwiseinteracting with the Visual Studio extensibility model.Running From Within Visual StudioThe most convenient way to do this is to set up a custom tool entry specifying the path to NUnitas the command. For a VS2003 C# project, you can use $(TargetPath) for the arguments and$(TargetDir) for the initial directory.With Visual Studio VS2005 this becomes a bit harder, because that release changed the meaningof the Target macros so they now point to the intermediate obj directories rather than the finaloutput in one of the bin directories. Here are some alternatives that work in both versions: $(ProjectDir)$(ProjectFileName) to open the VS Project rather than the assembly. If you use this approach, be sure to rename your config file accordingly and put it in the same directory as the VS project file. $(ProjectDir)bin/Debug/$(TargetName)$(TargetExt) to run the assembly directly. Note that this requires hard-coding part of the path, including the configuration.If you would like to debug your tests, use the Visual Studio Debug | Processes… menu item toattach to NUnit after starting it and set breakpoints in your test code as desired before runningthe tests.Using Console Interface to Debug ApplicationsWhen the nunit-console program is run in debug mode under Visual Studio, it detects that it isrunning in this mode and sends output to the Visual Studio output window. Output is formattedso that double clicking any error or failure entries opens the appropriate test file at the locationwhere the failure was detected.Opening Visual Studio ProjectsWhen Visual Studio support is enabled, the File Open dialog displays the following supportedVisual Studio project types: C#, VB.Net, J# and C++. The project file is read and theconfigurations and output assembly locations are identified. Since the project files do not containinformation about the most recently opened configuration, the output assembly for the firstconfiguration found (usually Debug) is loaded in the GUI. The tree shows the project as thetoplevel node with the assembly shown as its descendant.
    • Beginning with NUnit 2.2.2, you may also open a Visual Studio project by dragging it to the guitree control.When tests are run for a Visual studio project, they run just as if the output assembly had beenloaded with one exception. The default location for the config file is the directory containing theproject file and it’s default name is the same as the project file with an extension of .config. Forexample, the following command would load the tests in the nunit.tests assembly using theconfiguration file nunit.tests.dll.config located in the same directory as the dll. nunit.exe nunit.tests.dllOn the other hand, the following command would load the tests using the configuration filenunit.tests.config located in the same directory as the csproj file. nunit.exe nunit.tests.csprojThe same consideration applies to running tests using the console runner.Opening Visual Studio SolutionsWhen Visual Studio support is enabled, solution files may be opened as well. All the outputassemblies from contained projects of the types supported will be loaded in the tree. In the casewhere all contained projects are located in the subdirectories beneath the solution, it will bepossible to load and run tests using this method directly.Beginning with NUnit 2.2.2, you may also open a Visual Studio solution by dragging it to the guitree control.When a solution contains projects located elsewhere in the file system, it may not be possible torun the tests – although the solution will generally load without problem. In this case, the ProjectEditor should be use to modify and save the NUnit test project so that there is all referencedassemblies are located in or beneath the application base directory.Adding Visual Studio Projects to the Open Test ProjectWhen Visual Studio support is enabled, the Project menu contains an active entry to add a VSproject to the loaded project. The output assembly will be added for each of the configurationsspecified in the VS project.NUnit ExtensibilityNUnit is designed to be extended in a number of ways.Extensions to the NUnit framework - the part of NUnit that is referenced by tests - usually takethe form of Custom Constraints, written by users to encapsulate tests that pertain to their specificprojects.
    • Extending the features found within NUnit itself depends on the use of NUnit Addins. Currently,The Addin mechanism only supports extensions to the NUnit core - the part of NUnit that buildsand executes test suites. However, the API that is used provides for the future ability to extendthe client side of NUnit, including the GUI.Custom Constraints (NUnit 2.4 / 2.5)You can implement your own custom constraints by creating a class that inherits from theConstraint abstract class, which supports performing a test on an actual value and generatingappropriate messages. The class includes two abstract methods, which you must override andfour virtual methods with default implementation that may be overridden as needed:public abstract class Constraint{ ... public abstract bool Matches( object actual ); public virtual bool Matches( ActualValueDelegate del ); public virtual bool Matches<T>( ref T actual ); public abstract void WriteDescriptionTo( MessageWriter writer ); public virtual void WriteMessageTo( MessageWriter writer ); public virtual void WriteActualValueTo( MessageWriter writer ); ...}Your derived class should save the actual argument to Matches in the protected field actual forlater use.The MessageWriter abstract class is implemented in the framework by TextMessageWriter.Examining the source for some of the builtin constraints should give you a good idea of how touse it if you have special formatting requirements for error messages.Custom Constraint SyntaxNUnit includes classes that implement a special constraint syntax, allowing you to write thingslike...Assert.That( myArray, Is.All.InRange(1,100) );Of course, the NUnit constraint syntax will not be aware of your custom constraint unless youmodify NUnit itself. As an alternative, you may use the Matches(Constraint) syntactic elementin order to write code like...MyConstraint myConstraint = new MyConstraint();Assert.That( myArray, Has.Some.Matches(myConstraint) );NUnit Addins
    • NUnit originally identified tests in the time-honored way used in many xUnit test frameworks.Test classes inherited from the frameworks TestCase class. Individual test case methods wereidentified by having names starting with "test..."With NUnit 2.0, we introduced the use of attributes to identify both fixtures and test cases. Useof attributes in this way was a natural outcome of their presence in .NET and gave us a way ofidentifying tests that was completely independent of both inheritance and naming conventions.However, by moving away from an inheritance-based mechanism we no longer had an easy wayfor others to extend NUnits internal behavior. NUnit Addins are intended to fill that gap,providing an mechanism to introduce new or changed behavior without modifying NUnit itself.Extension Points, Extensions and AddinsNUnit provides a number of Extension Points, places where it is possible to extend its behavior.Because NUnit works with various hosts and uses separate AppDomains to run tests, ExtensionPoints are categorized into three types: Core, Client and Gui. Each of these types is supported bya different Extension Host.An NUnit Addin provides enhanced functionality through one or more extensions, which itinstalls at identified Extension Points. Each Addin is characterized by the types of extensions itsupplies, so that an Extension Host knows whether to invoke it.Note: In the current release, only Core extensions are actually supported. An Addin maycharacterize itself as a Client or Gui extension and will be listed as such in the Addins Dialog,but no other action is taken.Addin Identification, Loading and InstallationNUnit examines all assemblies in the bin/addins directory, looking for public classes with theNUnitAddinAttribute and implementing the IAddin interface. It loads all those it finds asAddins.NUnitAddinAttribute supports three optional named parameters: Type, Name and Description.Name and Description are strings representing the name of the extension and a description ofwhat it does. If no name is provided, the name of the class is used. Type may be any one or acombination of the ExtensionType enum members: [Flags] public enum ExtensionType { Core=1, Client=2, Gui=4 }The values may be ored together, allowing for future Addins that require extensions at multiple levelsof the application. If not provided, Type defaults to ExtensionType.Core.
    • The IAddin interface, which must be implemented by each Addin, is defined as follows: public interface IAddin { bool Install( IExtensionHost host ); }The Install method is called by each host for which the addin has specified an ExtensionType.The addin should check that the necessary extension points are available and install itself,returning true for success or false for failure to install. The method will be called once for eachextension host and - for Core extensions - each time a new test domain is loaded.The Install method uses the IExtensionHost interface to locate extension points. It is defined asfollows: public interface IExtensionHost { IExtensionPoint[] ExtensionPoints { get; } IExtensionPoint GetExtensionPoint( string name ); ExtensionType ExtensionTypes { get; } }The ExtensionPoints property returns an array of all extension points for those extensions thatneed the information. The ExtensionTypes property returns the flags for the type of extensionsupported by this host, allowing, for example, Gui extensions to only load in a Gui host.Most addins will only need to use the GetExtensionPoint method to get the interface to aparticular extension point. The IExtensionPoint interface is defined as follows: public interface IExtensionPoint { string Name { get; } IExtensionHost Host { get; } void Install( object extension ); void Remove( object extension ); }Once again, most addins will only need to use one method - the Install method in this case. Thismethod passes an extension object to the Extension Point where it is installed. Generally,extensions do not need to remove themselves once installed, but the method is provided in anycase.With NUnit 2.5, an additional interface, IExtensionPoint2 is available. It derives fromIExtensionPoint and also allows setting the priority order in which the extension will be calledin comparison to other extensions on the same extension point. The interface is defined asfollows: public interface IExtensionPoint2 : IExtensionPoint { void Install( object extension, int priority );
    • }Only extension points that use a priority scheme implement this interface. In general, extensionpoints with a priority scheme will use a default value for priority if the Install method without apriority is called.In the NUnit 2.5 release, only the TestDecorators extension point implementsIExtensionPoint2.Extension Point DetailsDepending on the particular extension point, the object passed will need to implement one ormore interfaces. The following ExtensionPoints are implemented in this release of NUnit: SuiteBuilders TestCaseBuilders TestDecorators TestCaseProviders DataPointProviders EventListenersFor examples of implementing each type of extension, see the Extensibility samples providedwith NUnit. More complete examples are available in the code of NUnit itself, since NUnit usesthe same mechanism internally.SuiteBuilders (NUnit 2.4)PurposeA SuiteBuilder is an addin used to build a test fixture from a type. NUnit itself uses aSuiteBuilder to recognize and build TestFixtures.Extension PointAn addin may use the host to access this extension point by name: IExtensionPoint suiteBuilders = host.GetExtensionPoint("SuiteBuilders" );InterfaceThe extension object passed to Install must implement the ISuiteBuilder interface: public interface ISuiteBuilder { bool CanBuildFrom( Type type ); Test BuildFrom( Type type ); }
    • CanBuildFrom should return true if the specified Type is one from which the builder is able tocreate a fixture. This usually involve examining the Type and its attriutes.The BuildFrom method should return a test fixture completely populated with its contained testcases. Return null if it is not possible to build a fixture using the provided Type.TestCaseBuilders (NUnit 2.4)PurposeTestCaseBuilders create Tests based on a MethodInfo. NUnit uses several TestCaseBuildersinternally to create various kinds of TestMethods.Extension PointAddins use the host to access this extension point by name: IExtensionPoint testCaseBuilders = host.GetExtensionPoint("TestCaseBuilders" );InterfacesThe extension object passed to Install must implement either the ITestCaseBuilder or theITestCaseBuilder2 interface: public interface ITestCaseBuilder { bool CanBuildFrom( MethodInfo method ); Test BuildFrom( MethodInfo method ); } public interface ITestCaseBuilder2 : ITestCaseBuilder { bool CanBuildFrom( MethodInfo method, Test suite ); Test BuildFrom( MethodInfo method, Test suite ); }NUnit will call ITestCaseBuilder2 if it is available. Otherwise ITestCaseBuilder will be used.The CanBuildFrom method should return true if the addin can build a test from the MethodInfoprovided. Some TestCaseBuilder addins are only intended to apply to methods within a specifictype of fixture. The suite argument of the ITestCaseBuilder2 interface may be used to make thisdetermination.The BuildFrom method should return a test constructed over the MethodInfo provided as anargument or null if the method cannot be used.
    • TestDecorators (NUnit 2.4)PurposeTestDecorators are able to modify a test after it has been constructed.Extension PointAddins use the host to access this extension point by name: IExtensionPoint testDecorators = host.GetExtensionPoint("TestDecorators" );InterfaceThe extension object passed to Install must implement the ITestDecorator interface: public interface ITestDecorator { Test Decorate( Test test, MemberInfo member ); }The Decorate method may do several things, depending on what it needs to accomplish: 1. Return test unmodified 2. Modify properties of the test object and return it 3. Replace test with another object, either discarding the original or aggregating it in the new test.Depending on what the decorator does, it may need to run ahead of other decorators or afterthem. Decorators should be installed using the Install method overload that takes a priority. Thepriorities range from 1 to 9 and decorators with lower priority values are installed first. Thefollowing standard values are defined for use if desired: DecoratorPriority.Default = 0 DecoratorPriority.First = 1 DecoratorPriority.Normal = 5 DecoratorPriority.Last = 9TestCaseProviders (NUnit 2.5)PurposeTestCaseProviders are used with parameterized tests to provide the specific test cases that will beused in calling the test.Extension PointAddins use the host to access this extension point by name:
    • IExtensionPoint listeners = host.GetExtensionPoint("ParameterProviders" );InterfaceThe extension object passed to Install must implement either the ITestCaseProvider or theITestCaseProvider2 interface: public interface ITestCaseProvider { bool HasTestCasesFor( MethodInfo method ); IEnumerable GetTestCasesFor( MethodInfo method ); } public interface ITestCaseProvider2 : ITestCaseProvider { bool HasTestCasesFor( MethodInfo method, Test suite ); IEnumerable GetTestCasesFor( MethodInfo method, Test suite ); }NUnit will call ITestCaseProvider2 if it is available. Otherwise ITestCaseProvider will beused.HasTestCasesFor should return true if the provider is able to supply test cases for the specifiedmethod. If a provider only wants to be used on certain types of tests, it can examine the providedMethodInfo and the suite for which the test is being constructed and return true or false based onwhat it finds.The GetParametersFor method should return a list of individual test cases. Each test case may beexpressed as a ParameterSet, as an array of arguments or as a custom object containing one ormore of the following properties: Arguments RunState NotRunReason ExpectedExceptionType ExpectedExceptionName ExpectedExceptionMessage Result Description TestNameThe ParameterSet class provides all these properties and may be used to avoid the overhead ofreflecting on the properties.Notes: 1. Most providers will delegate one of the interface implementations to the other if they implement both.
    • 2. TestCaseProviders that use data from the fixture class should use ITestCaseProvider2 interface so that they are able to access any arguments supplied for constructing the fixture object. 3. Providers that acquire data from outside the fixture will usually be able to work with ITestCaseProvider alone. 4. The ITestCaseProvider2 interface was added in the NUnit 2.5.1 release.DataPointProviders (NUnit 2.5)PurposeDataPointProviders are used to supply data for an individual parameter of a parameterized testmethod.Extension PointAddins use the host to access this extension point by name: IExtensionPoint listeners = host.GetExtensionPoint("DataPointProviders" );InterfaceThe extension object passed to Install must implement either the IDataPointProvider or theIDataPointProvider2 interface: public interface IDataPointProvider { bool HasDataFor( ParameterInfo parameter ); IEnumerable GetDataFor( ParameterInfo parameter ); } public interface IDataPointProvider2 : IDatapointProvider { bool HasDataFor( ParameterInfo parameter, Test parentSuite ); IEnumerable GetDataFor( ParameterInfo parameter, TestparentSuite ); }NUnit will call IDataPointProvider2 if it is available. Otherwise IDataPointProvider will beused.The HasDataFor method should return true if the provider is able to supply data for thespecified parameter. If a provider only wants to be used on certain types of tests, it can examinethe supplied ParameterInfo and its associated MethodInfo and Type and/or the parent test suite.The GetDataFor method should return a list of individual values to use for the suppliedparameter in running the test.
    • Notes: 1. Most providers will delegate one of the interface implementations to the other if they implement both. 2. DataPointProviders that use data from the fixture class should use IDataPointProvider2 interface so that they are able to access any arguments supplied for constructing the fixture object. 3. Providers that acquire data from outside the fixture will usually be able to work with IDataPointProvider alone. 4. The IDataPointProvider2 interface was added in the NUnit 2.5.1 release.EventListeners (NUnit 2.4.4)PurposeEventListeners are able to respond to events that occur in the course of a test run, usually byrecording information of some kind. Note that EventListeners called asynchronously with respectto test execution and are not able to affect the actual execution of the test.Extension PointAddins use the host to access this extension point by name: IExtensionPoint listeners = host.GetExtensionPoint( "EventListeners");InterfaceThe extension object passed to Install must implement the EventListener interface: public interface EventListener { void RunStarted( string name, int testCount ); void RunFinished( TestResult result ); void RunFinished( Exception exception ); void TestStarted(TestName testName); void TestFinished(TestResult result); void SuiteStarted(TestName testName); void SuiteFinished(TestResult result); void UnhandledException( Exception exception ); void TestOutput(TestOutput testOutput); }You must provide all the methods, but the body may be empty for any that you have no need of.
    • Tips for Writing ExtensionsAn Extenders Guide will be published in the future. At the moment, writing an extension is a bitof an adventure. Extension authors are advised to join the nunit-developer list and post questionsand comments there.For the moment, the following tips may be of assistance. The nunit.core.interfaces assembly is intended to be stable in the future while the nunit.core assembly will change from release to release. Right now, both assemblies are still in flux, but extensions that depend solely on the interfaces assembly will have a much better chance of surviving NUnit version changes. Unfortunately, this is rather difficult to do without duplicating a great deal of NUnit code. Most of the add-in samples provided with NUnit are currently version dependent. If you place the definition of a custom attribute in the same assembly as your add-in, then user tests are dependent on the add-in assembly. If the add-in is version-dependent, then the user tests will also be version-dependent. We suggest placing any types referenced by user tests in a separate assembly, particularly if your extension relies on nunit.core. If using Visual Studio, set Copy Local to false for any references to nunit.core or nunit.core.interfaces. This is especially important if you are also building NUnit itself. There is currently no mechanism to allow decorators to apply in a particular order. NUnit applies decorators in the order in which they are returned through reflection, which may vary among different runtimes. Avoid trying to "stretch" the existing extension points to do more than they were intended to do. Rather, let us know what further extension points you would like to see!Release NotesNUnit 2.5.7 - Version 2.5.7.10213 - August 1, 2010Features The new TestContext class allows tests to access information about themselves. The following properties are supported: o TestName gets the name of the test o Properties gets the test properties dictionary o State gets the TestState o Status gets the TestStatus Notes: 5. This is an experimental feature and could change in future releases. It is not included in the docs at this time. 6. TestState and TestStatus are intended for use in a TearDown method. Consult the intellisense for values of each enumeration.
    • 7. TestStatus should preferred over TestState for compatibility with future releases.Bug Fixes 570162 FileNotFoundException when loading .nunit file 595683 NUnit console runner fails to load assemblies 611325 Allow Teardown to detect if last test failed 611938 Generic Test Instances disappearNUnit 2.5.6 - Version 2.5.6.10205 - July 24, 2010Features ReusableConstraint provides reusability of constraint expressions within the test code. This feature is experimental. The Mono 4.0 profile is now listed in the Gui when support for it is detected. Multiple test names may be supplied to the console /run option. Dictionaries and Hashtables may be tested for equality without regard to order of entries. PNunit has been updated to match the latest release available. DirectoryAssert, xxxx and xxx are now marked as Obsolete.Bug Fixes 441022 Setup not called when test method inherited 498656 TestCase should show array values in GUI 532488 Constraints from ConstraintExpression/ConstraintBuilder are not reusable 548841 [Explicit] does not get overridden if there is another category exclude 570162 FileNotFoundException when loading .nunit file 571256 NUnit 2.5.5 Console Runner Requires /framework flag to run with .NET 4 574408 DirectoryAssert fails to recognise the sub folder using IsWithin 590717 Category contains dash or trail spaces is not selectable 590970 Static TestFixtureSetUp/TestFixtureTearDown methods in base classes are not run 591622 When SetUp method fails, no clear indication in GUI 595996 Missing files in source package 600554 NUnit uses wrong priority-scheme for addins 600555 NullReferenceException when ISuiteBuilder.BuildFrom(Type) returns null 600627 Assertion message formatted poorly by PropertyConstraint 601108 Duplicate test using abstract test fixtures 601129 Mono 4.0 not supported 601645 Parameterized test should try to convert data type from source to parameter 602798 NUnitConfiguration.MonoExePath returns wrong path 604861 Console runner /run option should allow multiple test names 605432 ToString not working properly for some properties 605793 Multiple instances of Nunit runners, which use nunit-agent, cannot be run in parallel 607924 PNUnit is out of date 608875 NUnit Equality Comparer incorrectly defines equality for Dictionary objects 606548 Deprecate Directory Assert
    • 609509 Test assembly file lock in version 2.5.5NUnit 2.5.5 - Version 2.5.5.10112 - April 22, 2010Features The Runtime Version dropdown on the Project Editor dialog now includes only major and minor version numbers like 2.0 or 4.0. When loading the tests, these versions are resolved to the highest version of the particular runtime available on your system. You may still enter a complete version number in the text box if desired. The DatapointsAttribute may now be specified on properties and methods as well as fields. For parameters of type T, the attribute now supports members of Type IEnumerable<T> in addition to arrays of the parameter Type. Timeouts are now suppressed when running under a debugger.Bug Fixes FileNotFoundException when test assembly is built for x64 platform. Config files not found with /domain:Multiple. SetCultureAttribute ignored on parameterized test methods. NUnit not recognizing .NET 4.0 RC or Final Release. TestFixtureTearDown in static class not executed Failing tests in sample files AssertSyntaxTests.cs and AssertSyntaxTests.vb. Invalid XML character in TestResult.xml when a test case string argument uses certain control or unicode characters.NUnit 2.5.4 - Version 2.5.4.10098 - April 8, 2010Features NUnit now defaults to running an assembly under the runtime version for which it was built. If that version is not available, a higher version may be used. See the Runtime Selection page for details. ProjectEditor now provides a Default selection for the runtime version to be used. The XML result file format has been enhanced to provide additional information needed to identify and report on theories and also includes extended result states such as Inconclusive, Invalid, Error and Cancelled. The EmptyConstraint (Is.Empty) may now be used with a DirectoryInfo to test whether the directory is empty. Datapoints for boolean and enum arguments are now generated automatically for theories. The cache path for shadow copying is now saved in the NUnit settings file rather than in the config files. The settings dialog may be used to change it if necessary.Bug Fixes NUnit crashing when a message contains ]]> Replace compile-time exclusion of code from Mono with run-time test
    • Message associated with Assert.Inconclusive() not shown in XML Category on test case clashes with category on the test method Console crash when specifying /domain:Single with multiple assemblies Incorrect relative path causing problems in saving projects Message associated with Assert.Pass() not shown in XML Tests with ExpectedException compiled against NUnit 2.4 always pass under 2.5 Datapoints with a null value were not being passed correctly to theories Error in XML output with FSharp.Net Documentation refers to files missing from Windows install Parameterized test fixtures with null parameters not handled correctly Theories now work as designed, failing when no data satisfies the assumptions Target framework of net-3.5 was causing console to crash Mono stack traces are now parsed correctly in the Gui Test failures under .NET 1.1 Thread CurentPrincipal set in TestFixtureSetUp not maintained between testsNUnit 2.5.3 - Version 2.5.3.9345 - December 11, 2009Note: This is the first release of NUnit on Launchpad.Features Test execution under .NET 4.0 is now supported. It may be selected in the Gui runner or using the console runner /framework option. NUnit test projects may specify .NET 4.0 as the required framework to be used for loading the the project. PlatformAttribute allows testing for .NET 4.0. The distribution now includes nunit-agent-x86.exe, which is used for running tests in a separate process under nunit-x86.exe or nunit-console-x86.exe when the target framework is .NET 2.0 or greater. Static methods Contains.Substring() and Contains.Item() have been added to the NUnit syntax for compatibility with NUnitLite. Non-public test fixtures are now allowed in all cases, whether the TestFixtureAttribute is present or not. Abstract classes may now be marked with TestFixtureAttribute to indicate that derived classes are to be treated as test fixtures. The abstract class is no longer marked as invalid. Fixtures without tests are no longer shown as non-runnable but are simply executed. If the fixture setup or teardown does not cause an error, they are reported as inconclusive.Bug Fixes Reloading tests in the Gui no longer uses the default runtime if a different runtime was previously selected. Thread principal is now saved before each test and restored afterward eliminating failures under .NET 4.0. Assume.That() overload with a message no longer results in test failure. An expected Result of null is now handled correctly on parameterized tests. Duplicate caching of metadata has been eliminated, resolving a load performance problem when many methods are inherited from a base class.
    • The names of nested generic and non-generic classes are now displayed correctly. Assert.Catch<T> now correctly returns exception type T rather than System.Exception. ValueSourceAttribute now works correctly when used with an external type. The /domain=None option on nunit-console once again works correctly. Parameterized test fixture names are now displayed with the actual arguments used so that failures may be associated with the correct instantiation of the fixture. Test labels for generics are now displayed correctly by the console runner and in the Gui text output tab. Generic fixtures without type attributes provided are now shown as non-runnable rather than causing a runtime error. (1) Use of an unknown file type in the console command line no longer causes an error. (2) A number of tests that ran incorrectly under Linux have been fixed. A number of tests failing under .NET 4.0 have been fixed.Notes 1. As a side effect of this fix, TestFixtureAttribute on a base class is overridden by a TestFixtureAttribute on the derived class. 2. This was originally reported as "crash when using /option in linux."NUnit 2.5.2 - Version 2.5.2.9222 - August 10, 2009Note: This is the last release of NUnit using source code maintained on Sourceforge. The CVSrepository there will be kept, but no longer updated. After this release, the source is beingmaintained on Launchpad at http://launchpad.net/nunit-2.5.Framework The new SetUICultureAttribute allows setting CurrentUICulture for the duration of a test method, fixture or assembly. The TestFixture, TestCase and TestCaseData attributes have been enhanced to allow ignoring an individual fixture instance or test case. Two new named parameters are provided: o Ignore may be set to true to ignore an item. o IgnoreReason may be set to specify the reason for ignoring the item. If IgnoreReason is set to a non-empty string, then setting Ignore is optional. Assert.Catch has been added with several overloads. It differs from Assert.Throws in accepting exceptions derived from the one that is specified. Like Assert.Throws, it returns the exception thrown when it succeeds so that further tests can be made on it. The Throws syntax has a number of new additions: o ThrowsTargetInvocationException, ThrowsArgumentException and Throws.InvalidOperationException provide a shorter syntax for testing for these common exception types. o Throws.InnerException applies any constraints to the InnerException of the exception that was thrown rather than to the exception itself. o InnerException can also be used in constraint expressions - see the documentation for an example.
    • Bug Fixes Data from a TestCaseSource in a separate class from the tests is now handled correctly. Arguments specified using TestCaseData are now used correctly. Comparing the a stream to itself no longer causes an error. TimeoutAttribute is now permitted on an assembly as documented. Clear All and Clear Failures buttons are now displayed correctly depending on whether Checkboxes are displayed in the Gui. The console runner option descriptions have been revised to more clearly indicate what each option does. Running special tests that do not use the nunit.framework assembly no longer causes a null reference exception. Console Runner option descriptions have been edited for accuracy. Gui TreeView now updates correctly when the order of tests has changed. An exception in TearDown now displays the actual exception at the top of the stack rather than a TargetInvocationException.NUnit 2.5.1 - Version 2.5.1.9189 - July 8, 2009Framework A new TestResult state has been defined for tests cancelled by the user. Results with ResultState.Cancelled are reported as a type of failure and no longer generate an ApplicationException. Parameterized test fixtures with TestCaseSource or ValueSource data are now constructed using the appropriate parameterized constructor when test cases are being created. This avoids the need for a default constructor and permits use of member data initialized from the fixture parameters in creating the test data. The TestCaseData class now supports use of a string or other array type as the sole argument value, without the need to nest that array in an object array. Abstract classes marked with TestFixtureAttribute are no longer reported as ignored or non- runnable. Note: This was changed in 2.5 but was omitted from the release notes. The methods in the Text class are now marked as obsolete. For string constraints, use one of the following at the start of an expression: o Is.StringContaining o Is.StringStarting o Is.StringEnding o Is.StringMatching Within an expression (afer Not, Some, All, And, Or, etc.) you may use o Contains or ContainsSubstring o StartsWith o EndsWith o Matches
    • ThrowsConstraint now has a constructor taking an ActualValueDelegate in addition to the constructor that takes a TestDelegate. This allows simpler use of Lambda expressions under C# 3.0, but requires users of pre-3.0 compilers to disambiguate their delegates by use of an explicit return expression.Core Individual test cases under a parameterized test are no longer sorted by name within the test group but are run (and shown in the Gui) in the order in which the data is retrieved. Note: Since the order of retrieval of custom attributes is not guaranteed by the CLR, the order of test cases will not necessarily match the textual ordering of attributes in the source code. The order of tests will vary across different compilers and CLR versions as well. The XML test result file now contains a count of inconclusive results.Gui The default icons in the Gui tree have been updated. Alternative icons placed by the user in the directory containing nunit.uikit.dll may now be in PNG format. Icons are now recognized for Skipped and Inconclusive status in addition to Success, Failure and Ignored. A new setting option allows the user to disable checking for the existence of files in the Recent Files list before listing them. This prevents NUnit from appearing to freeze when the file is on a network path that is no longer connected.Extensibility The ITestCaseProvider2 and IDatapointProvider2 interfaces extend ITestCaseProvider and IDatapointProvider with methods that include the fixture for which the test case is being built. Providers may implement either the old or the new interface, but the new interface is required if the data source is contained in the test fixture itself so that the fixture may be constructed with the proper parameters in the case of a parameterized fixture.Bug Fixes Lambda in Throws constraint was not compiling correctly. Null reference exception is no longer thrown when adding an assembly to a new project that has not yet been saved. Dispose is now called on disposable types created while loading test case parameters. Installations that copy NUnit to a single folder (no lib or framework folders) now work correctly. Test Assemblies menu item is no longer enabled when no test was loaded The Text Output tab of the Settings dialog no longer causes an exception when invoked from the mini-gui. Errors in various copyright statements were fixed and the year updated to 2009. Control characters in test arguments are now escaped in the display. Additional control characters are now escaped in error messages. Miscellaneous typographic corrections were made to the documentation.
    • NUnit 2.5 Final Release - Version 2.5.0.9122 - May 2, 2009Framework A new syntax element, Matches(Constraint), allows use of custom constraints, predicates or lambda expressions in constraint expressions. The MessageMatch enum used with ExpectedExceptionAttribute has been extended with a new value StartsWith, indicating that the exception message must start with the string provided. TestCaseAttribute now supports a MessageMatch property.Gui The File menu now allows selecting an alternate runtime, such as Mono, on a machine with multiple CLR implementations installed. This feature is still considered experimental and may change in the future. The combo box in the Project Editor allowing selection of a particular runtime type such as Mono for loading the test has been re-enabled.Bug Fixes Provided a workaround to a Mono 2.4 bug in handling remote references to an interface, where the provider is running under MS .NET and the implementation is explicit. Fixed a problem with the display of line numbers from a German language stack trace, with lines terminating in a period. The Console Runner display now shows the settings for ProcessModel, DomainUsage and RuntimeFramework actually provided, before resolution of any defaults. Removed references in the docs to pages that no longer exist.NUnit 2.5 Release Candidate - Version 2.5.0.9117 - April 27, 2009General The installation now uses a lib subdirectory to hold dlls. The build script target names have been changed to make more sense. In particular, package now builds the default package and targets not intended to be called directly are no longer listed as Main Targets by the -projecthelp option.Framework The following Constraints now use the NUnit definition of equality in comparing items, which may lead to changed behavior of some tests. o UniqueItemsConstraint o CollectionContainsConstraint o CollectionEquivalentConstraint o CollectionSubsetConstraint
    • The constraints listed now accept the IgnoreCase and Using modifiers, which work exactly as they do with EqualConstraintCore Caching is now used to reduce the time required to load tests.Gui A new submenu under File allows selecting a runtime version under which to reload the tests. Reloading in this way does not affect any runtime version setting in the project file. The project editor now provides a combo box listing known versions of the runtime. Other versions may still be entered in the edit box. Cross-CLR execution (for example, running Mono from .NET) has been disabled in the Gui, since it isnt yet implemented. The new stack trace display now follows the NUnit Font settings. The stack display uses the general gui font, while the source code display uses the fixed font. The separate settings for Recent Files under .NET 1.1 and .NET 2.0 have been combined, since the Gui now runs exclusively under .NET 2.0. The time required to restore the visual state of the tree after reloading has been substantially reduced, especially for large numbers of tests.Bug Fixes Use of a long assembly name for the ApplicationName of the AppDomain was causing excessively long paths in the shadow cache. The Using modifier of EqualConstraint now works as expected for string operands. TestCaseAttribute.ExpectedExceptionMessage is no longer ignored. The max number of files setting was not being saved when modified in the Gui Settings dialog. As a temporary fix, the pnunit.tests.dll has been moved to the same directory as pnunit- agent.exe and pnunit-launcher.exe, since pnunit tests dont allow for setting an appbase separate from the location of the test assembly.NUnit 2.5 Beta 3 Release - Version 2.5.0.9096 - April 6, 2009General The Gui is now built against .NET 2.0 only. Tests may still be run under .NET 1.x by running in a separate process. The Visual Studio 2003 solution has been removed. Framework and other components may still be built under .NET 1.x through the NAnt script. The nunit.framework.extensions assembly has been removed from the build.Framework EqualConstraint has been enhanced with several new modifiers, which may be used immediately after the Within(...) modifier to indicate how a numeric tolerance value should be interpreted.
    • o Ulps = as units in the last place (floating point only) o Percent = as a percentage of expected value o Days = as a TimeSpan in days o Hours = as a TimeSpan in hours o Minutes = as a TimeSpan in minutes o Seconds = as a TimeSpan in seconds o Milliseconds = as a TimeSpan in milliseconds o Ticks = as a TimeSpan in ticks The comparison constraints (GreaterThan, LessThan, etc.), RangeConstraint and CollectionOrderedConstraint may now be used with objects that implement IComparable<T>. The syntax used for specifying that a collection is ordered has changed. Is.Ordered is now a property. The property name to use for ordering is specified using Is.Ordered.By(name). The following constraints now accept a Using modifier to indicate that a user-specified comparer should be used: o EqualConstraint o GreaterThanConstraint o GreaterThanOrEqualConstraint o LessThanConstraint o LessThanOrEqualConstraint o RangeConstraint o CollectionOrderedConstraint The provided comparer may be any of the following: o IComparer o IComparer<T> o Comparison<T> In addition, EqualConstraint may use: o IEqualityComparer o IEqualityComparer<T>NUnit 2.5 Beta 2 Release - Version 2.5.0.9015 - January 15, 2009Framework NUnit now includes an implementation of Theories, similar to what is found in JUnit. Support for Theories is provided by the Theory, Datapoint and Datapoints attributes and by the Assume.That method. For more information and further links, see the TheoryAttribute documentation page. AssertionHelper has been updated so that the Expect overloads now include the signatures newly introduced for Assert.That. The code for Assert is now generated. This is in addition to the files that were generated in beta- 1. AfterConstraint has been renamed to DelayedConstraint.
    • Console The console runner now supports a /framework option, which allows running the tests under a different version of the CLR.Gui The Gui is now able to display the source code for test or production code from the stack trace, provided the assemblies contain source code information and the source code is available. Contributed by Irénée Hottier. Reloading the tests after changing settings in a way that modifies the shape of the tree is now handled correctly. The Settings Dialog now opens to the page that was last viewed.NUnit 2.5 Beta 1 Release - Version 2.5.0.8332 - November 27, 2008General Most of the code for elements of the constraint syntax is now generated. This allows us to more rapidly deploy new constraints with their corresponding syntax. The file SyntaxElements.txt contains the specifications used in generating the code. At this time, we are including both this file and the generated files with the NUnit source, so that those working in other areas of the code dont have to regenerate them each time they make changes. The nunit.core.extensions assembly has been removed from the build. Features that were previously in that assembly are now in the nunit.core assembly. All third-party addins have been removed from the build and must be downloaded separately from their own sites. An index of such addins is maintained on the NUnit site.Framework New attributes are provided to control use of threads by tests. All of the following may be used on methods, classes or assemblies: o RequiresThreadAttribute forces creation of a new thread and may optionally indicate the desired ApartmentState for the thread. o RequiresSTAAttribute causes the test to run in the STA. A new thread is created only if the parent is not in the STA. On methods, the .NET-provided STAThreadAttribute may also be used. o RequiresMTAAttribute causes the test to run in the MTA. A new thread is created only if the parent is not in the MTA. On methods, the .NET-provided MTAThreadAttribute may also be used. o TimeoutAttribute is used to set the timeout for tests. When used on classes or assemblies, the timeout value is used as the default timeout for all subordinate test cases. Test cases with a timeout value run on a separate thread and return a failure message if the timeout is exceeded. The MaxTimeAttribute specifies a miximum elapsed time for a test case. If the test takes longer, it is reported as a failure. This attribute was previously available as an extension.
    • Note: Unlike TimeoutAttribute, MaxTimeAttribute does not cause the test to be cancelled, but merely times it. RepeatAttribute causes a test case to be executed multiple times. This attribute was previously available as an extension. PairwiseAttribute now works, generating all pairs of each argument value. [In earlier betas, it was unimpemented and simply generated all combinations.] PropertyAttribute has been modified internally to use a dictionary of name/value pairs rather than just a single name and value. This feature is not exposed for direct use, but may be accessed by derived attributes that want to apply multiple named values to the test. For a simple example of usage, see the code for RequiredThreadAttribute. The presence of TestCaseSourceAttribute on a method is now sufficient to identify it as a test. As with TestCaseAttribute, use of TestAttribute is optional. Assert.That has been extended to allow a delegate or a reference as the argument. By default, these are evaluated before being used by the constraint supplied but some constraints may delay evaluation. The new AfterConstraint is an example. An additional overload of Assert.Throws allows passing a constraint or constraint expression as the first argument. The syntax for AttributeConstraints has been enhanced so that further tests may be applied to properties of the attribute rather than just checking for its existence. AfterConstraint allows delaying the application of a constraint until a certain time has passed. In its simplest form, it replaces use of a Sleep in the code but it also supports polling, which may allow use of a longer maximum time while still keeping the tests as fast as possible. The After modifier is permitted on any constraint, but the delay applies to the entire expression up to the point where After appears. Note: Use of After with a simple value makes no sense, since the value will be extracted at the point of call. Its 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.Core NUnit now supports running tests in a separate process or in multiple processes per assembly. In addition, tests run in a separate process may use a different runtime version from that under which NUnit is running. Note: In the Beta release, execution of tests under Mono from a copy of NUnit that is running under .NET is not yet supported.Console The new /process:xxxxx command line option is used to run tests in a separate process or in multiple processes per assembly. A new commandline option, /timeout:nnnn allows you to specify a default timeout value, which is applied to each test case in the run without a Timeout specified.
    • Gui The Assembly Info display now uses a scrolling text box and has been enhanced to show information about the Process and AppDomain in which the test is running and the runtime version under that is being used. The Project Editor now allows setting the ProcessModel and DomainUsage for a project to control how that project is loaded and run. It also supports setting a target runtime framework for each configuration. If the target runtime is different from the runtime under which NUnit is running, the tests will be run automatically in a separate process under the target runtime. The Project Editor no longer reloads the tests as each individual change is made. Tests are reloaded after the editor is closed and only if changes have been made to the overall project configuration or to the active configuration. The "Options" dialog is now called "Settings."Extensibility The implementation of constraints has been changed so that it is no longer necessary to create an additional "Modifier" class when a custom constraint takes modifiers. If you simply implement each modifier as a property or method returning the object itself, it will be usable in the full range of constraint expressions. Note: Although you can readily create custom constraints, this release of NUnit still lacks the ability to create new syntactic elements without rebuilding the framework.Bug Fixes Loading a single assembly and then adding another assembly using the Add Assembly menu item was not working correctly. Reloading tests after settings changes was failing when the new settings changed the shape of the tree in such a way that the new tests didnt match the old ones correctly. The Reload Project menu item was followed by a prompt asking if the current project state should be saved first and making the reload work in an unexpected way if you answered yes. A class without a TestFixture attribute, containing only TestCase methods, without any Tests, was not recognized as a test fixture. Assert.DoesNotThrow was failing to display a user message. Xml documentation for Assert.IsNotEmpty and Assert.AreEqual was incorrect. CollectionAssert.AreEqual and EqualConstraint were not working with IEnumerables that were not also Collections. PlatformAttribute now distinguishes correctly between Vista and Windows 2008 Server.NUnit 2.5 Alpha 4 Release - Version 2.5.0.8528 - September 14, 2008Framework Use of the TestFixtureAttribute is now optional in designating classes that contain tests. More than one method may now be marked with the SetUp, TearDown, TestFixtureSetUp and TestFixtureTearDown attributes. Setups in a base class are executed before those in a derived
    • class and teardowns are executed in the reverse order. If there are multiple setups or teardowns defined at the same level, the order is unspecified so this practice is not generally recommended. The FactoryAttribute and TestCaseFactoryAttribute introduced in alhpa-3 have been removed. The new TestCaseSourceAttribute allows specification of the name of the source of test cases and - optionally - the type providing the source if it is not the same as the type that contains the test. Only one source may be specified per attribute but the attribute may be applied more than once to indicate multiple sources. It is now possibe to specify Categories and Properties on test cases defined using the TestCaseData class. Named fields, properties or methods may be used to provide values for individual method parameters using the new ValueSourceAttribute. New constraints and corresponding syntactic constructs are provided: o Is.InRange tests that a value lies within a specified range. o Has.Attribute() tests for the presence of a specified attribute on a type. o Is.AssignableTo allows reversing the operands of AssignableFrom for increased clarity in the code and in any error messages when the actual value is of the derived type. o Throws.Exception allows testing the exception thrown by a delegate in place and provides the ability to make arbitrary tests on the caught exception. Throws.TypeOf() and Throws.InstanceOf() are provided as shorthand for the commonly used Throws.Exception.TypeOf() and Throws.Exception.InstanceOf. o Throws.Nothing provides for testing that a delegate does not throw. While it doesnt do much, it serves the purpose of converting an unexpected error into a test failure. The parsing of constraint expressions written using the fluent interface has been reorganized internally, with the following benefits: o Meaningless sequences like "...Null.Null..." or "...And.Or..." will no longer compile - the NUnit tests actually verify this by attempting to compile them. o Syntax modifiers like Within and IgnoreCase are now only accepted - and shown by intellisense - on constraints that actually make use of them. o New And and Or infix operators are provided. o The With provides some ability to group constraints. Note: Operators are evaluated in the following order:5. Postfix modifiers (highest) 6. Not Operator 7. And operator (see below) 8. Or operator (see below) 9. With operator 10. Some, None and All operators 11. And operator when followed directly by Some, None or All 12. Or operator when followed directly by Some, None or All 13. Overloaded operator & 14. Overloaded operator | (lowest) Operators of equal precedence associate left to right.
    • The "syntax helper" classes, Is, Has, Text and List have been moved to the NUnit.Frameworknamespace, since they seem to have entered the mainstream. NUnit 2.5 is able to recognize, load and run NUnitLite tests. PropertyConstraint now works with Types when testing for the existence of a named property.Core Experimental support is provided for running tests in a separate process. Currently, this is only exposed in the Gui runner. NUnit recognizes a special attribute on the config element of the nunit project file, runtimeFramework, which may be set to "net-1.1" or "net-2.0." This causes use of the appropriate runner if tests are run in a separate process. Note: Both of the above features are experimental and somewhat fragile. Results are expected to vary for different installations and we ask that problems be reported.Gui The Addin Dialog now shows an error message for any addin that fails to load. (from 2.4.8) The TestLoader settings dialog provides an option for running tests in a separate process. The Assembly Info display now shows two runtime versions for each test assembly: the one for which it was built and the one under which it is currently loaded.Extensibility The RequiredAddinAttribute is now only permitted at the assembly level.Bug Fixes The Gui output panes were failing to use a fixed font. (from 2.4.8)NUnit 2.5 Alpha 3 Release - Version 2.5.0.8189 - July 7, 2008General NUnit now uses a new version numbering scheme. The first three dot-separated values represent the release level, as before, while the fourth is a build number tied to the date of the release. This alpha release, for example, is numbered 2.5.0.8189. The NUnit source now includes a VS2008 project, in addition to the existing VS2005 and VS2003 projectsFramework DataSourceAttribute has been replaced with FactoryAttribute. The new attribute may refer to any field, method or property that provides test cases consistent with the signature of the method on which it appears. The naming of this attribute is still a bit unsatisfactory and it may change in the final release.
    • The new TestCaseFactoryAttribute class may be used to mark a field, method or property that provides test cases. It specifies the argument types of the test cases that will be provided and is used to identify the cases to be used when the name of a factory is not specified. Data may be specified for individual arguments of a parameterized test using the new attributes: ValuesAttribute, RangeAttribute and RandomAttribute. By default, test cases are created using every possible combination of the items provided. Attributes on the test method may specify how data is combined. This release includes SequentialAttribute, CombinatorialAttribute (the default) and PairwiseAttribute. However, Pairwise combination is not yet implemented, so that attribute is currently ignored. TestFixture classes may now be generic. They must be marked with or or more instances of TextFixtureAttribute using the new constructor that takes an array of Types. NUnit will instantiate the fixture multiple times, using the type arguments provided. Parameterized test methods may now be generic. NUnit will deduce the correct implementation to use based on the types of the parameters provided. The new RequiredAddinAttribute may be used to mark tests, fixtures or assemblies, indicating the name of any addin that is required to run the tests. If the addin is not present, the test, fixture or assembly is marked NotRunnable. A new assertion and corresponding constraint IsOrdered has been added. (contributed by Simone Busoli) PlatformAttribute has been extended to accept the new keywords NT6, Vista and Win2008Server. Note: In the current alpha release, NUnit is unable to distintuish between Vista and Windows 2008 Server. Either of them will match all the above values.Gui Properties with a collection for a value are now displayed displayed as a comma-separated list in the properties window.Extensibility The IParameterProvider interface has been replaced with ITestCaseProvider. The ParameterProviders extension point has been renamed to TestCaseProviders. A new extension point, DataPointProviders, has been added to support extensions that provide data for individual test parameters. Extensions must implement the IDataPointProvider interface. A simpler method of providing new data point extensions based on attributes applied to the parameter itself is also available. Such attributes may be derived from ValuesAttribute and do not require any special addin in order to work.Bug Fixes NUnit tests of AssertThrows were not working on systems using non-English cultures. Domains were not unloading correctly in some circumstances. Unloading is now done on a separate thread. An NUnitSettings.xml file of zero length was causing a crash. (from 2.4.8)
    • Invoking the gui with /exclude:XXX, where XXX is a non-existent category, was causing all tests to be excluded. (from 2.4.8) Categories were not working properly on repeated tests. (from 2.4.8) A serious memory leak was fixed in the NUnit test runners. (from 2.4.8) Static SetUp and TearDown methods were not being called in a SetUpFixture. The current directory used when executing addins that load tests was not correctly set.NUnit 2.5 Alpha 2 Release - May 7, 2008Note: Since this is an alpha level release, the features are not complete and some features presentin this release may be removed or changed in future releases.General This release includes pNUnit, an extended NUnit runner for distributed parallel tests. The pNUnit program was developed at Codice Software for use in testing the Plastic SCM and has been contributed to NUnit. For more info about using pNUnit see the pNUnit site. The install now offers Typical, Complete and Custom options. Selecting Typical gets you the NUnit framework, core, console runner and Gui. To install pNUnit, any of the bundled addins or the NUnit tests, select Complete or Custom.Extensibility The RowTestExtension, which was merged into the nunit extension dlls in Alpha-1, is now provided as a separate addin. This is the general approach we plan to take with regard to any bundled addins, since it permits the creator of an addin to provide updates separately from the NUnit release. This release includes the CSUnitAddin extension, which allows the running of CSUnit tests under NUnit. The csunit.dll must be available in order to run the tests.NUnit 2.5 Alpha 1 Release - April 18, 2008General There are no longer separate distributed packages for .NET 1.1 an 2.0. Both the binary zip and msi packages contain subdirectories for .NET 1.1 and 2.0. In the case of the msi, the user may elect to install either or both of them. The Visual Studio solutions and projects are now in a directory tree that is parallel to the source tree. This eliminates problems where the VS2003 and VS2005 builds were interfering with one another and makes room for adding VS2008. NUnit is now built using NAnt 0.86 beta 1 The windows installer is now created using WiX 2.0.5085Framework Two new attributes have been added to support passing arguments to test methods:
    • o TestCaseAttribute allows the programmer to specify the arguments and a number of optional parameters inline. o DataSourceAttribute identifies a static property that will provide the arguments and other parameters.Two new constraints have been added to permit testing of application-created paths, withoutrequiring that they exist in the file system. The following syntax is supported: o Is.SamePath(string) o Is.SamePathOrUnder(string)The DirectoryAssert class has been added, providing the following Methods: o AreEqual(DirectoryInfo, DirectoryInfo) o AreEqual(string, string) o AreNotEqual(DirectoryInfo, DirectoryInfo) o AreNotEqual(string, string) o IsEmpty(DirectoryInfo, DirectoryInfo) o IsEmpty(string, string) o IsNotEmpty(DirectoryInfo, DirectoryInfo) o IsNotEmpty(string, string) o IsWithin(DirectoryInfo, DirectoryInfo) o IsWithin(string, string) o IsNotWithin(DirectoryInfo, DirectoryInfo) o IsNotWithin(string, string)The method Assert.Throws(Type expectedException, TestSnippet code) has been added toprovide more control over tests of expected exceptions. TestSnippet is a delegate, which may ofcourse be supplied anonymously under .NET 2.0. If the correct exception type is thrown, theactual exception is returned from the method, allowing further verification to be performed.The Assert.DoesNotThrow method may be used to verify that a delegate does not throw anexception.The Assert.Pass method allows early termination of a test with a successful result.The Assert.Inconclusive method allows returning the new Inconclusive result state.NUnit now includes added funtionality in the .NET 2.0 build of the framework. The followingadditional features are supported: o All Asserts and Constraints work with nullable types. o Some Asserts allow an alternate generic syntax for convenience:  Assert.IsInstanceOf<T>(object actual);  Assert.IsNotInstanceOf<T>(object actual);  Assert.IsAssignableFrom<T>(object actual);  Assert.IsNotAssignableFrom<T>(object actual);  Assert.Throws<T>(TypeSnippet code);The following obsolete interfaces, classes and methods have been removed: o The IAsserter interface o The AbstractAsserter class o The Assertion class o The AssertionFailureMessage class o The old NUnit.Framework.TestCase class used for inheriting test classes o The Assert.DoAssert() method o Two ExpectedExceptionAttribute(Type, string) constructor o Two ExpectedExceptionAttribute(string, string) constructor
    • The syntactic constructs in the SyntaxHelpers namespace have been moved to the NUnit.Framework.Syntax.CSharp namespace. The old namespace may still be used for existing classes, but will not be supported after the 2.5 release.Core NUnit now allows use of static methods as tests and for SetUp, TearDown, TestFixtureSetUp and TestFixtureTearDown. Failures and Errors are now distinquished internally and in summary reports. Methods that are not run because they are invalid are also reported separately.Console The summary report now displays Errors, Failures, Inconclusive, Ignored and Skipped tests separately. More detailed information on non-runnable tests and setup failures is provided. The console summary report is no longer created using a stylesheet, which renders the /transform option meaningless. The option has been removed.Gui The default gui display now uses a single tab for all text output. For users upgrading from an earlier release, the current settings are honored. If you wish to change to the new default, use the Restore Defaults button on the Text Output settings dialog. The final test run display shows a more detailed summary: passed tests, errors, failures, inconclusive, non-runnable, skipped and ignored. The status bar now displays errors and failures separately in. The tree display shows non-runnable tests in red and inconclusive tests in orange. Inconclusive tests are temporarily listed on the Tests Not Run tab for this alpha release.Extensibility A new extension point ParameterProviders allows addins to provide data for parameterized tests. The following extensions are included in the nunit.core.extensions and nunit.framework.extensions assemblies: o The MaxTime extension, which was previously a sample. o The RowTest extension, which remains an alternative to NUnits native TestCase syntax. o The XmlConstraint extension, which allows comparing two xml files