Unit test framework nunit attributes of attributes (2)

Source: Internet
Author: User

 

Next

 

14, repeatattribute (nunit 2.5)

Repeatattribute is used to specify how many times a test case should be run. If any one fails, the following times will not run and only one error will be reported.

15, requiredaddinattribute (nunit 2.5)

Requiredaddin attribute is used to specify the required assembly to run correctly. If the specified assembly is not referenced, the entire program is marked as unexecutable.

In the three trial versions, this feature can be applied to classes or methods, but from the next version, it will only be used to the Assembly.

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(){  ...}  }}

16, requiresmtaattribute (nunit 2.5)

RequiresmtaattributeThe application specifies on methods, classes, or assembly that the code is to run in multi-threaded apartment. If the parent test is not run in the MTA thread, creates a new MTA thread.

17, requiresstaattribute (nunit 2.5)

It requires that the test run in a single-threaded apartment ). It will also create a new stathread if the parent test is not running in the stathread.

18, requiresthreadattribute (nunit 2.5)

It requires that the method, class, or assembly to be applied should run in an independent thread. You can also add an optional parameter to the constructor to specify the apartmentstate of the thread. With this method, a new thread will be created no matter whether you have a parameter or not.RequiresstaattributeOrRequiresmtaattributeIt is created only when the apartmentstate of the current thread is not suitable.

// All tests running this Assembly will be created with a new thread [Assembly: requiresthread]... // test class [testfixture, requiresthread] public class fixtureonthread {// all methods in this class will create an independent thread} [testfixture] public class anotherfixture {[test, requiresthread] public void testrequiringthread () {// This test requires an independent thread} [test, requiresthread (apartmentstate. sta)] public void testrequiringstathread () {// an independent stathread will be created to run this test }}

19, sequentialattribute (nunit 2.5)

SequentialattributeA test method is used to generate a test case using the data items provided by parameters. Each data is used only once. If a parameter has multiple attributes, the order of the data items is uncertain. However, this sequence remains the same for a given system and runtime.

For example:

[Test, Sequential]public void MyTest(    [Values(1,2,3)] int x,    [Values("A","B")] string s){    ...}

Three trials will be conducted as follows:

MyTest(1, "A")MyTest(2, "B")MyTest(3, null)

20, setcultureattribute (nunit 2.4.2)

This attribute changes the region information of the current test and can be applied to the method and class level. It should be noted that the impact of this change will be set to the initial value after the entire class or method is executed. If you only want to determine whether to perform this test in the current region information, use the culture attribute.

Only one region information can be determined. running the test in multiple regions information will be added in future versions. However, by building your test code to a private method and then calling the test method in different regions, you can still achieve the same purpose.

21, setuicultureattribute (nunit 2.5.2)

Setuiculture attribute is used to set the region information of the UI. For usage, refer to the preceding setcultureattribute.

22, setupattribute (nunit 2.0/2.5)

This feature is used within the test class to provide features that will be executed before each test method is called. Before nunit2.5, only one setup method is required and one instance method is required. Starting from 2.5, it can be instance or static, and there can be multiple: Multiple setup methods should be defined at different levels of inheritance as much as possible. That is to say, the setup method can be inherited. The setup method defined by the parent class is also called before the subclass test method is called. Before 2.5, only one setup method is allowed. If you want to use the setup function of the base class and add your own functions, you should call the setup method of the base class in the subclass. After 2.5, you only need to add the function you want to attach to the subclass. nunit will call the setup method of the base class before the subclass method is called. Avoid defining multiple setup methods in a class as far as possible, because their execution sequence is unpredictable.

If the setup method fails or an exception is thrown, the test will be stopped and the report fails or an exception is thrown.

23, setupfixtureattribute (nunit 2.4)

This feature indicates that this class of the current namespace contains only one-time setup and teardown methods. The labeled class can only have one setupattribute method and one teardownattribute method. The setup method of this class will be executed once before any test classes in this namespace are executed, and the teardown method will be executed once after all tests in this namespace are executed.

A namespace can have only one setupfixture. setupfixture outside of any namespace applies these functions to the entire assembly.

This class should be public and should have a default constructor to ensure that nunit can construct instances of this class.

24, suiteattribute (nunit 2.0/2.4.4)

Suite attribute is used to define a set that contains a series of tests. It is only used in command line applications./FixtureOption. The methods introduced after 2.0 are used to replace the previous methods inherited from the testsuite class.

The suite mechanism depends on a static attribute marked with suiteattribute. After 2.0, it returns the value of testsuite. This method has some problems: it needs to reference A nunit that is not commonly used by users. core Assembly: in this way, the test can be transplanted to other versions only after re-compilation, and the running may be abnormal in different core assembly versions.

After 2.4.4, a set of test class objects or types will be returned for attributes marked with suiteattribute. It can also containTestfixturesetupAndTestfixtureteardownTo provide one-time setup and teardown mechanisms for suite test classes.

// Use namespace nunit in 2.0. 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 ;}}// use namespace 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 (); // you can also use this method. // suite. add (typeof (onetestcase); // suite. add (typeof (assemblytests); // suite. add (typeof (nonamespacetestfixture); Return suite ;}}}}

Note:

1. You cannot directly include a separate test method in the suite. If you want to do so, use the earlier method and create an inherited from nunit. core. but this is not recommended.

2. By default, suites will not be executed. It provides the purpose of testing a set that has a higher running level than all tests, these will only be executed when the/fixture option is applied in the command line.

Later versions may remove these two restrictions.

25, teardownattribute (nunit 2.0/2.5)

It is consistent with setup, except that it runs after each test method is run.

26, testattribute (nunit 2.0/2.5)

One method in this property tag test class is the test method. For backward compatibility, if a method starts with "test", it will also be considered as a test method, which is case-insensitive, however, this method is not supported in the configuration file of the test.

Starting from 2.5, the test method can be static and can contain parameters and return values, because nunit already knows how to process parameters and return values.

For the parameters of the test method, as we mentioned earlier, the parameters of multiple data items will create multiple test cases. There are some features that allow the parameter to be determined in an inline manner, some provide an independent method, attribute, or field. In addition, some attributes provide all parameters of the method, while some provide data for only one parameter. See the following table:

  Provide all parameters of the Method Provide data for a parameter
Inline mode Testcaseattribute Randomattribute
Rangeattribute
Valuesattribute
Independent Mode Testcasesourceattribute Valuesourceattribute

Some other features such as combinatorialattribute (default), pairwiseattribute, and sequentialattribute are added to the method to specify how to process these parameters.

If the signature of the test method is incorrect, the method is considered non-running and pointed out by the runner.

27, testcaseattribute (nunit 2.5)

TestcaseattributeAll parameters are provided for a test method, so that the method can use these parameters to complete a test.

For example, devidetest assigns corresponding parameters to each testcase to perform a test.

[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 );}
The execution result is:
DivideTest(12,3,4);DivideTest(12,2,6);DivideTest(12,4,3);

If the data format and parameters required for running the method are inconsistentConvert. changetype ()Make a transformation. Features may appear multiple times and can be used together with other features.

In addition, you can useResultTo specify the return value.

[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 );}

Nunit checks whether the returned value is equal to the given value.

Some other naming parameters are available:

Description

Set the description of this test.

Expectedexception

The type of exception that should be thrown during this operation.

Expectedexceptionname

The full name of the exception thrown during this operation.

Expectedmessage

An exception message is thrown.

Matchtype

MessagematchThe enumerated value indicates the matching method of the message value. (Refer to expectedexceptionattribute)

Testname

The name of this test. If no method name is specified, the parameter specified for this test will be combined as the name.

Ignore

If it is set to true, this test is ignored.

Ignorereason

Specifies the reason for the ignore. If it is not a null value, this operation is ignored by default.

In addition, when multiple testcaseattribute values are specified, the execution sequence of different systems or platforms may be different.

28, testcasesourceattribute (nunit 2.5)

AndTestcaseattributeAll features provide data for testing,TestcasesourceattributeData is provided independently. It has two constructors:

TestCaseSourceAttribute(Type sourceType, string sourceName);TestCaseSourceAttribute(string sourceName);

If the sourcetype parameter is specified, this indicates the class that provides data. It should have a default constructor. If it is not specified, the class containing this test will be constructed.

The sourcename parameter specifies the name of the data source. It can be a field, attribute, or method, or an instance or a static data source. However, it must return an ienumerable or an object that implements ienumerable, the signature parameters of the test method must also be met.

For how to build a test case, nunit uses each data returned by the following enumerators:

1. If the object implementsNunit. Framework. itestcasedataIts attributes can be used for each use case. The following are the fields or attributes it exposes:

Arguments

OneObject []Type object, which is passed to the method as a parameter.

Categories

An ilist type is applied to various use cases.

Description

Set the test description attribute.

Expectedexception

The exception that should be thrown during this call.

Expectedexceptionname

Name of the thrown exception.

Properties

An idictionary type is also applied to various test cases. These values use the same propertiesattribute.

Result

The expected return value of the test method. The return value type must be compatible.

Testname

The name of the test. If not provided, the method name and the passed parameter value form the name.

Ignored

If it is set to true, this test routine is ignored.

Ignorereason

The reason for ignoring. If it is not a null value, this test routine will be ignored.

2. If it is an object [] object, its member will be used as a method parameter.

[Test, TestCaseSource("DivideCases")]public void DivideTest(int n, int d, int q){    Assert.AreEqual( q, n / d );}static object[] DivideCases ={    new object[] { 12, 3, 4 },    new object[] { 12, 2, 6 },    new object[] { 12, 4, 3 } };

3. If it is an array of other types, nunit can also be used as long as the type of this type matches the type of the method parameter. In the preceding example, if it is an interleaved array of int [], it can also be used.

Although you can useItestcasedataBut nunit still provides the testcasedate class to achieve the same purpose.

[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");    }  }  }

Of course, for the last yield code block, you can:

 TestCaseData data = new TestCaseData(0,0);      data.ExpectedException = typeof(DivideByZeroException;      data.TestName = "DivideByZero";      data.Description = "An exception is expected";      yield return data;

Testcasedata provides the following methods and attributes, which can be called in any order:

. Returns. Setcategory (string). Setproperty (string, string). Setproperty (string, INT). Setproperty (string, double). Setdescription (string). Setname (string). Throws (type). Throws (string). Ignore (). Ignore (string)

In addition, the sequence in which the data source provided by testcasesourceattribute is called is not predictable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.