At the earliest time, nunit used inheritance and naming conventions to confirm that methods or classes were used for testing. However, starting from 2.0, the custom feature custom attributes is used: in this way, you do not have to inherit a specific class and can freely define the class hierarchy. Without the naming conventions, you can name it according to the intent of the method.
All nunit attributes are included in nunit. in the Framework namespace, so every file should reference this namespace, and your test project should also reference nunit. framework. DLL assembly.
Starting from 2.4.6, The nunit attribute attributes is no longer a closed sealed, and any attribute attributes inherited from them will be recognized.
Nunit provides 36 Available attributes:
1, categoryattribute (nunit 2.2)
CATEGORY attribute provides a way to run the test by group. Either a test class or method can be specified as a specific category. The GUI and console runners can specify the classes that are included or excluded during running: in this way, only the test classes or methods of the specified classes are run, and others are not reported. The console runner uses the/include or/exclude parameter to specify a category. The GUI runner has a categories label that lists all categories and allows you to select the category to be run.
namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture] [Category("LongRunning")] public class LongRunningTests { [Test] [Category("Long")] public void VeryLongTest() { /* ... */ } }}
2, combinatorialattribute (nunit 2.5)
Combinatorialattribute is used in the test method. nunit generates a test case using a combination of methods and parameters. This attribute is called by default.
For example
[Test, Combinatorial]public void MyTest( [Values(1,2,3)] int x, [Values("A","B")] string s){ ...}
It will be run six times in the following ways:
MyTest(1, "A")MyTest(1, "B")MyTest(2, "A")MyTest(2, "B")MyTest(3, "A")MyTest(3, "B")
3, cultureattribute (nunit 2.4.2)
The culture attribute is used to specify the region information when the test class or method is running .. It does not affect the configuration. It is mainly used to determine whether to perform this test. If you want to change the configuration at runtime, you can use setculture attribute.
If the specified region information is not supported, it will be skipped. In the GUI runner, the test node is still gray and does not affect the status bar.
You can call this method to add it to the corresponding test class or method:
[Culture("fr-FR")][Culture(Exclude="en,de")]
4, description (nunit 2.4)
Description attribute adds a description to the test assembly, class, or method. This description appears in the output XML file and is displayed in the test property box.
[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() { /* ... */ } }}
5, expectedexceptionattribute (nunit 2.0 plus updates)
With this function, you can specify the exceptions that will be thrown during testing. It has several parameters and named parameters. You can call it in the following ways.
Specify the expected exception type: the test is successful when the specified exception is thrown.
// Introduced in 2.0, it must be a definite type [expectedexception (typeof (argumentexception)] public void testmethod (){...} // from 2.2.4, specify the type as a string without referencing the exception Assembly [expectedexception ("system. argumentexception ")] public void testmethod (){...}
Identify the error message of the exception: A second parameter is introduced from 2.1 to construct the value of the message attribute of the specified exception; from 2.2.4, similarly, a string parameter is used to indicate that constructors of the exception type are available. Methods below 2.4 are marked as not recommended, A new named parameter is used instead.
// Obsolete form:[ExpectedException( typeof( ArgumentException ), "expected message" )][ExpectedException( "System.ArgumentException", "expected message" )]// Prefered form:[ExpectedException( typeof( ArgumentException ), ExpectedMessage="expected message" )][ExpectedException( "System.ArgumentException", ExpectedMessage="expected message" )]
From 2.4, we can perform more tests on the message, not just equal. This requires the name of matchtype: it is an enumeration type.
Public Enum messagematch {// expect to be completely equal to exact, // expect the message to contain the specified string contains, // expect the message to conform to the given regular RegEx, /// expect message to start with the given string startswith}
For example, you can call this method to obtain the message containing "unspecified" that is expected to throw an exception ":
[ExpectedException( typeof( ArgumentException), ExpectedMessage="unspecified", MatchType=MessageMatch.Contains )]public void TestMethod(){...}
With the usermessage name parameter, you can also customize the prompt information when the expectedexception attribute condition is not met.
[ExpectedException( typeof( ArgumentException ), UserMessage="Custom message" )]public void TestMethod(){...}
Equivalent to try/catch in practice to handle exceptions, so the declaration of features is obviously complicated. Therefore, from 2.4, you can specify a method to handle exceptions.
General Exception ProcessorImplementationIexpectexceptioninterface:
public interface IExpectException{ void HandleException( System.Exception ex );}
This processor is only markedExpectedexceptionFeature is called. If you want to use this processor to handle all exceptions, you only need to specifyExpectedexceptionMark.
Of course, you may want to apply the processor to only a method. You can use handler to name the parameter:
[ExpectedException( Handler="HandlerMethod" )]public void TestMethod(){...}public void HandlerMethod( System.Exception ex ){...}
We can see that it is not implementedIexpectexception. In the future, we can designate this processor to any method that needs to be used, while other methods are marked without being specified.ExpectedexceptionWill call the general-purpose processor.
However, it should be noted that these processing methods may check exceptions and assert the associated attributes: Any failure information will be fed back in the test results like other assertions.
6. explicitattribute (nunit 2.2)
Unless it is displayed that the class or method for applying the explicit it attribute is selected to be run, it will be ignored at runtime. You can specify an optional parameter to indicate the reason for applying this feature.
namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture, Explicit] public class ExplicitTests { [Test, Explicit] public void ExplicitTest() { /* ... */ } }}
The above example only shows how to call the API. Generally, it will not be applied in both the class and its method, even though it will not report an error.
7, ignoreattribute (nunit 2.0)
Ignore attribute does not run classes or methods during testing. The status bar in the GUI turns yellow and the test is not running. This can be used when the test is temporarily not run, which is much better than comment out, because the code will still be compiled and will prompt that the test is not run at runtime.
8, maxtimeattribute (nunit 2.5)
MaxtimeattributeThe maximum running time of the test method is specified in milliseconds. If the running time is longer than the specified time, an error is reported. Note that it does not stop the test from running, but compares the running time with the specified time when the test is completed. Therefore, the priority of other assertions in the Code is higher than the time. If you want to stop a test that has been running for too long, you can use timeoutattribute.
9, pairwiseattribute (nunit 2.5)
This feature specifies that nunit should generate test cases using any possible pairs of values in the parameter items. This is a good way to generate a large number of tests when more than three parameters are combined. However, in the current version, it can be used, but it adopts the previous working method of combinatorial attribute.
10, platformattribute (nunit 2.2.2)
Platform attribute is used to specify the platform for running the test class or method. Platform names that do not distinguish the size string are used to specify the platform to include or exclude. If the running platform does not meet the conditions specified by the attribute, this test will be ignored and will not affect other tests and statuses.
[Platform("NET-2.0")][Platform(Exclude="Win98,WinME")]
The names of supported platforms are as follows:
- Win
- Win32
- Win32s
- Win32windows
- Win32nt
- WinCE
- Win95
- Win98
- Winme
- Nt3
- NT4
- Nt5
- Nt6
- Win2k
- WINXP
- Win2003server
- Vista
- Win2008server
- Win2008serverr2
- Windows 7
- UNIX
- Linux
- Net
- Net-1.0
- Net-1.1
- Net-2.0
- Net-4.0
- Netcf
- Sscli
- Rotor
- Mono
- Mono-1.0
- Mono-2.0
11, propertyattribute (nunit 2.4)
Property attribute sets an attribute for a class or method in the form of a key-value pair.
namespace NUnit.Tests{ using System; using NUnit.Framework; [TestFixture, Property("Location",723)] public class MathTests { [Test, Property("Severity", "Critical")]public void AdditionTest() { /* ... */ } }}
It does not affect the running of the test, but will appear in the output XML file and the test attribute box in the GUI. If possible, you can write an extension to process the specified property or obtain the value through reflection in a test.
In addition, you can inheritPropertyattributeCreate a custom attribute. You can use it in the subclass to provide a protected constructor to create an attribute and set the value. Nunit itself also uses this method to create some attributes.
12, randomattribute (nunit 2.5)
RandomattributeGenerate a series of random numbers based on a parameter of the test method. It has the following structures:
public Random( int count );public Random( double min, double max, int count );public Random( int min, int max, int count );
By default, nunit generates a test case based on all the data provided in the parameter. The following example will be run 15 times: each X value has a combination of five random numbers between-1.0 and 1.0.
[Test]public void MyTest( [Values(1,2,3)] int x, [Random(-1.0, 1.0, 5)] double d){ ...}
13, rangeattribute (nunit 2.5)
Rangeattribute is used in the parameters of the test method to specify a series of numbers. It has the following structures:
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 );
Example:
[Test]public void MyTest( [Values(1,2,3) int x, [Range(0.2,0.6,0.2] double d){ ...}
This test will be run nine times:
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)
Other features are described below.