[ZT] use unit test tool NUnit in. NET Environment

Source: Internet
Author: User
Tags xunit
Author: shanyou Www.ASPCool.comTime: 17:42:13 views: 4454 

Introduction

Writing unit tests is a verification and design behavior. Similarly, it is a kind of document writing behavior. Writing Unit Tests avoids a considerable number of feedback loops, especially feedback loops for functional verification.

Although it takes years for program developers to write Unit Tests to test their own program code, however, most Unit Tests are written after the main program code has been designed and written. Most program developers have the same experience. It is difficult to add Unit Test after the main program code is written, unit Test is usually the first skip step under time pressure. this article introduces. NUnit, a unit testing tool for the. NET platform.

What is Unit Tests )?



There are many types of tests in the program design process. unit tests are only one of them. unit tests cannot ensure that the program is perfect, but in all tests, unit testing is the first and most important step. Unit testing is a self-testing task by programmers. To put it simply, unit testing is to test whether the code writer has produced the expected results based on the methods it imagined. Many articles have made a lot of in-depth analysis on the importance of unit testing. NUnit is an automated unit testing framework for Net. It helps you easily complete unit testing. Like the well-known JUnit, NUnit is a member of the xUnit family. It's: http://www.nunit.org.



Introduction to NUnit Framework



The NUnit 2.1 discussed in this article is a very different version from its ancestors (other frameworks. Other xUnit family versions usually have a base class. The test classes (test cases) You want to write must be inherited from the base class. In addition, there is no other way for you to write Unit Tests. Unfortunately, this imposes a lot of restrictions on many programming languages. For example, Java and C # can only allow single inheritance (single inheritance ). That is to say, if you want to refactor your Unit Tests code, you will encounter some restrictions, unless you introduce some complicated inheritance hierarchies (class inheritance level ). With. NET, everything is different. NET introduces a new concept of program development-Attributes (attribute), which solves this annoying problem. Attributes allows you to add metadata (metadata that describes program code) to your program code ). In general, Attributes does not affect the execution of the main program code. Its function is to add additional information on the code you write. Attributes is mainly used in documenting your code (comment your program code), but Attributes can also be used to provide additional information about Assembly, even if other programs have never seen this Assembly, you can also use this information. This is basically what NUnit 2.1 does. In NUnit 2.1, there is a Test Runner Application (responsible for executing the Unit Tests Program). This Test Runner will scan the program code that you have compiled, you can also know from the Attribute which classes are test classes and which methods are the test methods to be executed. then, Test Runner uses. NET Reflection technology (in.. NET Framework provides. reflection namespace, so that we can easily get it.. NET component information. This function is useful when you want to obtain detailed information about a component in use or query a component information during running) to execute these test methods. For this reason, you no longer need to let your test classes inherit from the so-called common base class. The only thing you need to do is to use the correct Attribute to describe your test classes and test methods. NUnit provides many different attributes, allowing you to freely write the unit tests you want. These attributes can be used to define test fixtures (see the next section), test methods, and setup and teardown methods (the methods for preparation and follow-up ). In addition, other attributes can be used to set the expected conditions, or Test Runner is required to skip some test methods and not execute them.



About TestFixture Attribute



TestFixture attribute is mainly used on the class, which indicates that the class contains the test methods to be executed. When you add this attribute to a class definition, Test Runner checks the class to see if the class contains test methods. The following code demonstrates how to use TestFixture Attribute. (All program code in this article is written in C #, but you should know that NUnit is also used in other. NET programming languages, including VB. NET. See NUnit related files.



Namespace UnitTestingExamples

{



Using System;

Using NUnit. Framework;



[TestFixture]

Public class SomeTests

{

}

}



The class using TextFixture Attribute must comply with another unique additional restriction, that is, a public default constructor (or no constructor is defined, which actually means the same ).



Introduction to TestFixtureSetUp and TestFixtureTearDown







These two functions are mainly used in TestFixture, which provides a set of functions before execution of any test run (TestFixtureSetUP) and after execution of the last test (TestFixtureTearDown ). Each TestFixture can have only one TestFixtureSetUp method and one TestFixtureTearDown method. If you use more than one TestFixtureSetUp and TestFixtureTearDown methods, you can compile the method but do not execute it. Note that a TestFixture can have a TestFixtureSetUp and a SetUp, or a TestFixtureTearDown and a TearDown method.



TestFixtureSetUp and TestFixtureTearDown are not convenient to use the SetUp and TearDown methods.



Generally, SetUp and TearDown attributes are used.







The following code demonstrates how to use TestFixtureSetUp/TestFixtureTearDown.



Namespace UnitTestingExamples

{



Using System;

Using NUnit. Framework;



[TestFixture]

Public class SomeTests

{

[TestFixtureSetUp]



Public void RunBeforeAllTests ()



{



Console. WriteLine ("TestFixtureSetUp ");



}



[TestFixtureTearDown]



Public void RunAfterAllTests ()



{



Console. WriteLine ("TestFixtureTearDown ");



}



[SetUp]



Public void RunBeforeEachTest ()



{



Console. WriteLine ("SetUp ");



}



[TearDown]



Public void RunAfterEachTest ()



{



Console. WriteLine ("TearDown ");



}



[Test]



Public void Test1 ()



{



Console. WriteLine ("Test1 ");



}



}



}







The program output will be the following result ::



TestFixtureSetUp



SetUp



Test1



TearDown



SetUp



Test2



TearDown



TestFixtureTearDown



If Test2 executes the output separately, the result will be:



TestFixtureSetUp



SetUp



Test2



TearDown



TestFixtureTearDown







About Test Attribute



The Test attribute is mainly used to mark the method in text fixture, indicating that the method needs to be executed by the Test Runner application. The method with the Test attribute must be public and return void, without any input parameters. If these rules are not met, the method is not listed in the Test Runner GUI, and the method is not executed when the Unit Test is executed. The code above demonstrates how to use this attribute.



Introduction to SetUp and Teardown Attributes



When writing Unit Tests, you sometimes need to make preparations or aftercare before or after each test method is executed. Of course, you can write a private method and call this special method at the beginning or end of each test method. Alternatively, you can use the SetUp and Teardown Attributes we will introduce to achieve the same purpose. As these two Attributes names mean, the method with Setup Attribute will be executed by test Runner before each Test method in the TextFixture is executed, methods With Teardown Attribute are executed by test Runner after each Test method is executed. Generally, Setup Attribute and Teardown Attribute are used to prepare required objects (objects), such as database connection. The code above demonstrates how to use this attribute.



ExpectedException Attributes Introduction



Sometimes, you want your program to produce certain exceptions under certain special conditions. Use Unit Test to Test whether the program generates exceptions as expected. You can use a try .. catch (catch) exception in the catch program section, and then set a boolean value to prove that the exception did occur. This method is feasible, but it takes too much effort. In fact, you should use this ExpectedException attribute to identify the exception that a method should produce, as shown in the following example:



Namespace UnitTestingExamples



{



Using System;



Using NUnit. Framework;



[TestFixture]

Public class SomeTests

{



[Test]



[ExpectedException (typeof (InvalidOperationException)]

Public void Test1 ()



{



// Do something that throws an InvalidOperationException

}



}



}



If the above program is executed, if the exception occurs and the type (type information) of this exception is InvalidOperationException, the test will pass the verification smoothly. If you expect your program code to produce multiple exceptions, you can also use multiple ExpectedException attributes at a time. However, a test method should only test one thing. It is not good to test multiple functions at a time. You should try to avoid this. In addition, this attributes does not check the inheirtance relationship, that is, if the exception generated by your program code is inherited from the subclass (subclass) of InvalidOperationException, this test will not pass verification during execution. In short, when you use this attribute, you must specify the expected type (type information) of the exception.



Introduction to Ignore Attributes



You may not use this attribute frequently, but it is very convenient to use it once necessary. You can use this attribute to indicate a test method, which is called "Test Runner" and skipped this method during execution. The method for using this Ignore attribute is as follows:



Namespace UnitTestingExamples

{

Using System;

Using NUnit. Framework;



[TestFixture]

Public class SomeTests

{

[Test]

[Ignore ("We're skipping this one for now.")]

Public void TestOne ()

{

// Do something...

}

}

}



If you want a temporary comment out of a test method, you should consider using this attribute. This attribute allows you to retain your test method. In the execution result of Test Runner, it will also remind you of the existence of the skipped test method.



Introduction to NUnit Assert Class



In addition to the attributes mentioned above, NUnit also has an important class that you should know how to use. This class is Assert class. Assert class provides a series of static methods for you to verify whether the results of the main program are the same as you expected. Assert class replaces the old Assertion class. The following is the method of this class:



Assert. IsTrue (bool );



Assert. IsFalse (bool );



Assert. IsNull (bool );



Assert. IsNotNull (bool );



Assert. AreSame (object, object)



Assert. AreEqual (object, object );



Assert. AreEqual (int, int );



Assert. AreEqual (float, float, float );



Assert. AreEqual (double, double, double );



Assert. Fail ();



An example of using this class is as follows:



Namespace UnitTestingExamples

{

Using System;

Using NUnit. Framework;



[TestFixture]

Public class SomeTests

{

[Test]



Public void TestEventLengthString ()



{



// Shocould return true



Bool bResult1 = Class1.CheckPalindrome ("ABCCBA ");



Assert. IsTrue (bResult1 );



// Shocould return false



Bool bResult2 = Class1.CheckPalindrome ("ABCDBA ");



Assert. IsFalse (bResult2 );



}



[Test]



Public void TestOddLengthString ()



{



// Shocould return true;



Assert. IsTrue (Class1.CheckPalindrome ("ABCDCBA "));



// Shocould return false



Assert. IsFalse (Class1.CheckPalindrome ("ABCDEBA "));



}



}

}







Execute your Tests



Now we have discussed the basic steps and methods for writing Unit Tests. Now let's take a look at how to execute the Unit Tests you wrote. In fact, it is very simple. There are two Test Runner applications written in NUnit: one is the window GUI program and the other is the console XML (command column) program. You can choose the method you like. Basically, there is no difference.

If you want to use the Test Runner app of the window GUI, you only need to execute the program and then tell it the assembly location of the test method you want to execute. This includes the assembly you wrote test methods, which is the class library (or executable, *. dll or *. exe) assembly, which contains the Test Fixtures mentioned earlier. When you tell Test Runner where your assembly is located, Test Runner will automatically load this asembly, and then list all the classes and test methods in the left column of the window. When you press the 'run' button, you will automatically execute all the listed test methods. You can also double click a test class or a test method to automatically execute this class or method.

The following figure shows how the Test Runner of the window is executed:




In some cases, especially when you want to add Unit Testing to the build script you write, you probably won't use the GUI Test Runner. When the build script is automatically executed, you usually paste the build result on the webpage or write it into the log file for record, for developers, managers, or customers to know the details by checking this record. In this case, you can use the console Test Runner application of NUnit 2.1. This Test Runner can pass in the assembly position as a parameter, and the Test execution result is an XML string. You can use XSLT or CSS to convert the XML result into HTML or other formats you want. If you need this function, check the information about the console Test Runner application in the NUnit file.

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.