Using the Unit Test tool in a. NET Environment NUnit

Source: Internet
Author: User
Tags assert inheritance reflection xunit
Writing unit tests is a validation behavior, but also a design behavior. Again, it is a document-writing behavior. Writing unit tests avoids a considerable amount of feedback loops, especially the feedback loops in functional validation.
Although the program developer writes the unit Tests to test the program code that they wrote for years, most of the units 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 the unit test after the main program code has been written, and the test is usually the first step to be skipped under the pressure of time. This article describes the NUnit of a. NET Platform Units testing tool.
What is the unit Tests (units test).
In the process of programming there will be many kinds of tests, the unit is only one of them, unit testing does not guarantee that the program is perfect, but in all tests, unit testing is the first link, but also the most important part. Unit testing is a task that is tested by the programmer. In simple terms, a unit test is the test code Writer's execution in the way it is conceived to produce the expected results. The importance of unit testing has been a lot of in-depth analysis of the article, there is no longer to repeat. NUnit is a net-ready automated Unit Testing framework that helps you to easily complete unit tests and is a member of the Xunit family, like Dingding's renowned junit. Its download address is: http://www.nunit.org.

NUnit Framework (NUnit Unit test framework) Introduction

   the nunit 2.1 discussed in this article is a very different version of its ancestors (other frameworks). Other Xunit family versions usually have a Base class (base class), and the test classes (test case) you want to write is inherit (inherited) from this base class. Besides, there is no other way to get you to write unit tests. Unfortunately, this is a big limitation for many programming languages. For example, Java and C # can only allow Single inheritance (single inheritance). In other words, if you want to refactor (refactor) your unit tests program code, you will encounter some limitations, unless you introduce some complex inheritance hierarchies (class inheritance level). There it is. NET then everything is different again. NET introduced a new program developed by the concept of  ─ attributes (attributes) to solve this annoying problem. Attributes allows you to add metadata (metadata, description of program code) on top of your program code. Generally speaking, attributes does not affect the execution of the main program code, and its function is to add additional information on top of the program code you are writing. Attributes is mainly used in  documenting your code (annotate your program code), but attributes can also be used to provide additional information about assembly. Other programs can use this information even if they have not seen the assembly. This is basically what nunit 2.1 do. Inside the nunit 2.1, there is a test runner application (responsible for executing the unit tests program), this test runner will scan you already compile (compile) Good program code, and from the attribute inside know which classes is test classes, which methods is to be executed test methods.  then,test  Runner uses the. NET Reflection Technology (the System.Reflection namespace is provided in. Net framework, which makes it easy to get. NInformation on ET components. This functionality becomes useful when you want to get the details of the component you are using, or when you are querying a component's information during the run, to perform 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 offers a number of different attributes that allow you to write freely about the unit tests you want. These attributes can be used to define test fixtures (see the next paragraph), test methods, and the methods of the setup and teardown (preparation and Aftermath methods). In addition, there are other attributes that can either set the expected exceptions or require Test runner to skip some test method.

Introduction to Testfixture Attribute

Testfixture attribute is mainly used in class, its role is to mark the class contains the need to perform test methods. When you add this attribute,test to the definition of a class, runner checks the class to see if the class contains Test methods. The following program 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 related files for NUnit.

Namespace Unittestingexamples
{

Using System;
Using Nunit.framework;

[Testfixture]
public class Sometests
{
}
}

The class that uses textfixture attribute needs to meet another unique additional constraint, that is, the need to have a public default constructor (or not to define any constructor, which actually means the same thing).

Introduction to Testfixturesetup and Testfixtureteardown



These two are mainly used in testfixture, the function of which is to provide a set of functions to perform any test run before (Testfixturesetup) and after the last Test execution (Testfixtureteardown). Each testfixture can only have a Testfixturesetup method and a Testfixtureteardown method. If more than one Testfixturesetup and Testfixtureteardown method can be compiled but not executed. Note that a testfixture can have a testfixturesetup and a setup, or you can have a testfixtureteardown and a teardown method.

Testfixturesetup and Testfixtureteardown are used for inconvenient use of the setup and Teardown methods.

General use of SetUp and teardown attributes.



The code below 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 output of the program will be the following result:

Testfixturesetup

SetUp

Test1

Teardown

SetUp

Test2

Teardown

Testfixtureteardown

If TEST2 performs the output separately, the result will be:

Testfixturesetup

SetUp

Test2

Teardown

Testfixtureteardown



Introduction to Test Attribute

Test attribute is mainly used to mark method in text fixture, which means that this method needs to be executed by test Runner application. Method with test attribute must be public and must return void, and there is no incoming parameter. If these rules are not met, this method is not listed in the test Runner GUI and will not be executed when the unit test is executed. The above program code demonstrates how to use this attribute.

Introduction to SETUP and teardown attributes

When writing unit tests, sometimes you will need to do some preparation or aftercare before executing each test method (or later). Of course, you can write a private method, and then call this particular method at the beginning or end of each test method. Alternatively, you can use the setup and teardown attributes we want to introduce to achieve the same goal. As the names of these two attributes mean, the method with the Setup attribute is executed by test runner before each test method in the Textfixture is executed, and the teardown The method of attribute is executed by test runner after each test method is executed. In general, the Setup attribute and teardown attribute are used to prepare some necessary objects (objects), such as database connection, and so on. The above program code demonstrates how to use this attribute.

ExpectedException Attributes Introduction

Sometimes you want your program to have some specific exception under certain special conditions. To test whether a program is expected to produce exception using unit test, you can use a try ... The Catch's program section to catch (capture) this exception, and then set a Boolean value to prove that exception did happen. This method is feasible, but it takes too much effort. In fact, you should use this expectedexception attribute to indicate which exception 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 this throws an InvalidOperationException
}

}

}

If the above program is executed, if the exception occurs, and the type of the exception is InvalidOperationException, this test will pass the validation successfully. If you expect your program code to produce multiple exception, you can also use multiple ExpectedException attributes at once. However, a test method should only test one thing, and testing multiple functions at a time is not a good idea, and you should try to avoid it. In addition, this attributes does not check inheirtance relationships, that is, if your program code produces exception that inherits from InvalidOperationException subclass (subclasses), This test will not pass validation when it is executed. In short, when you use this attribute, you need to be clear about which type of exception is expected.

Ignore Attributes Introduction

You probably won't use it very often, but this attribute is handy when you need it. You can use this attribute to mark a test method, called Test Runner, to skip this method while executing. 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 and, in the execution result of Test runner, will also remind you of the existence of the skipped test method.

Introduction to NUnit Assert class

In addition to the attributes mentioned above to mark the test program, NUnit has an important class you should know how to use. This class is the Assert class. Assert class provides a series of static methods that you can use to verify that the results of the main program are the same as what you expected. The Assert class replaces the old assertion class, and 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 ();

Examples of using this class are as follows:

Namespace Unittestingexamples
{
Using System;
Using Nunit.framework;

[Testfixture]
public class Sometests
{
[Test]

public void testeventlengthstring ()

{

Should return True

BOOL BRESULT1 = Class1.checkpalindrome ("ABCCBA");

Assert.istrue (BRESULT1);

Should return False

BOOL BRESULT2 = Class1.checkpalindrome ("Abcdba");

Assert.isfalse (BRESULT2);

}

[Test]

public void testoddlengthstring ()

{

should return true;

Assert.istrue (Class1.checkpalindrome ("ABCDCBA"));

Should return False

Assert.isfalse (Class1.checkpalindrome ("Abcdeba"));

}

}
}



Execute your tests.

OK, now that we've talked about the basic steps and methods of writing unit Tests, let's look at how to execute the unit Tests that you write. It's actually very simple. NUnit has two written test Runner applications: One is the window GUI program, the other is the console XML (command column) program. You are free to choose the way you like, and basically there is no difference.
If you want to use the window GUI's Test Runner app, you just need to execute the program and then tell it where you want to perform the assembly location of test method. The assembly that contains the test methods you wrote 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, test runner automatically load this asembly and then put all class and Test methods in the left column of the window. When you press the ' Run ' button, you automatically perform all the listed test methods. You can also double click one of the test classes, or a test method, which automatically executes only that class or method.
The bottom is what the window GUI Test runner does when it executes:


In some cases, especially if you want to add unit testing to your own build script, you probably won't be using GUI Test Runner. In the case of this automatic build script, you typically post the results of your builds on a Web page, or write a record in log file to allow the program developer, manager, or customer to know the details by checking the record. In this case, you can use NUnit 2.1 console Test Runner application. This Test runner can pass in the position of the Assembly as an argument, and the result of its testing execution is an XML string. You can use XSLT or CSS to translate this XML result into HTML, or whatever format you want. If you need to use this feature, check the NUnit file for information about console Test Runner application.

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.