Using unit test tool NUnit in .NET Environment

zhaozj2021-02-17  78

Introduction

Writing unit test is a verification behavior, a design behavior. Similarly, it is a behavior of writing documents. Write unit tests Avoid a considerable number of feedback cycles, especially feedback cycles in functional verification.

Although the program developers write Unit Tests (unit test) to test their own procedures, most of the Unit Tests is written in the main program code, after writing. Most of the program developers have the same experience. After the main procedure code is written, join the Unit Test is a difficult job, and under the pressure of time is usually the first step of being skipped. This article introduces a .NET platform unit test tool NUnit.

What is the Unit Tests (unit test)?

There will be many tests during the programming process, and the unit is only one of them. The unit test does not guarantee that the program is perfect, but in all the tests, the unit test is the first link, which is also the most important part. . Unit testing is a work that is tested by the programmer. Simply said that the unit test is whether the test code writer executes whether or not the expected result is created in terms of its way. There are many articles about the importance of unit testing, there are many in-depth analysis, and will not be described here. NUNIT is an automation unit test framework for NET. Its role is to help you make cellular test work, like a famous JUnit, is a member of the XUnit family. Its download address is: http://www.nunit.org.

NUNIT FRAMEWORK (NUnit Unit Test Framework)

The NUnit 2.1 discussed in this article is a very different version of its ancestors (other framework). Other XUnit family versions usually have an Base Class (Subject class), you have to write Test classes (test case) has INHERIT (inherited) from this base class. In addition, there is no other way to let you write Unit Tests. Unfortunately, this has a large limit for many program languages. For example, Java and C # can only allow Single Inheritance (single inheritance). That is, if you want Refactor (Reconstruction) Your Unit Tests program code, you will encounter some restrictions; unless you introduce some complex inheritance hierarchies (category inheritance level). Everything is different after .Net, .NET introduced a new program development concept - Attributes, solves this annoying problem. Attributes allow you to add Metadata on your program code (metadata, description program code). In general, Attributes do not affect the execution of the primary program code, and its function adds additional information to the program code. Attributes is primarily used in Documenting Your Code, but Attribute can also be used to provide additional information about Assembly, and other programs have not seen this Assembly, or use this. This is basically a thing for NUnit 2.1. In NUnit 2.1, there is a Test Runner Application (which is responsible for executing the Unit Tests program). This test runner scans you already compile, and knows which classes is Test Classes from Attribute, which Methods is needed. Test Methods executed. The test runner uses the .NET's Reflection technology (providing System.Reflection namespace in .NET Framework, this makes it easy to get information about .NET components. When you want to get it When the component is detailed, or when a component information is queried during operation, this feature will change very useful) to perform these Test Methods. For this reason, you no longer need to let your test classes inherit your self-called CommON Base Class. What you need to do is to describe your Test Classes and Test Methods using the correct Attribute. NUNIT offers many different Attributes that allows you to write free to write the Unit Tests you want. These Attributes can be used to define Test fixTures, Test Methods, and Methods for the SETUP and TEARDOWN (Methods). In addition, other Attributes can set the expected Exceptions, or require Test Runner to skip some Test Method not execution. TestFixTure Attribute Introduction

TestFixTure Attribute is mainly used on the Class, which is the function that the Class contains the test methods that needs to be executed. When you add this attribute in a Class's definition, Test Runner checks the Class to see if this class contains Test Methods. This program code demonstrates how to use TestFixTure Attribute. (All program code in this article use C # written, but you should know that NUnit is also used for other .NET programming, including VB.Net. See NUNIT's related files .Namespace UnitTestingExamples {

Using system; using nunit.framework;

[Testfixture] public class sometests {}}

Class using TextFixTure Attribute needs to meet another unique additional limit, you need to have a PUBLIC's Default Constructionor (or no CONSTRUCTOR, this is actually the same).

TestFixTureTUP and TestFixTureTeadown Introduction

These two are mainly used in TestFixTure, and their role is to provide a set of functions before performing any test run (TestFixTureTeteardown). Each TestFixTure can only have a TestFixTureTUP method and a TestFixTureTeartown method. If more than one TestFixTureTUP and TestFixTureTeadown methods can be compiled but not executed. Note that a TestFixTure can have a TestFixTureTUP and a setup, or you can have TestFixTureTeartown and a Teardown method.

TestFixTureTUP and TestFixTureTeadown are used in inconvenience to use the Setup and Teardown methods.

General conditions use Setup and Teardown Attributes.

This program code demonstrates how to use TestFixTureTUP / TestFixTureTeadown

Namespace UnitTestingExamples {

Using system; using nunit.framework;

[TestFixTure] public class sometests {[testfixtureetup]

Public void runbeforeAlltests ()

{

Console.writeline ("TestFixTureTup");

}

[TestFixTureTeartown]]

Public void RunafteralLtests ()

{

Console.writeline ("TestfixTureTeartown");

}

[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 results ::

TestfixTureTup

Setup

TEST1

TEARDOWN

Setup

TEST2

TEARDOWN

TestfixTureTeadown

If the result of the output of TEST2 separates the output is: TestFixTureTup

Setup

TEST2

TEARDOWN

TestfixTureTeadown

Introduction to Test Attribute

Test Attribute is primarily used to indicate the method in the text fixture, indicating that this Method needs to be executed by the Test Runner Application. There must be a PUBLIC, and there must be Return Void, and there is no incoming parameter. If these regulations are not met, this Method will not be listed in the Test Runner GUI, and this Method will not be executed when performing the Unit Test. The above program code demonstrates the method of using this Attribute.

Introduction to Setup and Teardown Attributes

When writing Unit Tests, sometimes you need to perform some preparatory or good work before performing each Test Method (or later). Of course, you can write a private Method and call this special method at one of the Test Method or the last side. Alternatively, you can use the SETUP and Teardown Attribute we need to reach the same purpose. Like the name of these two Attributes, the Method with Setup Attribute will be executed by Test Runner before each Test Method in this textFixture, and the Teardown Attribute's method will be executed at each Test Method. It was then executed by Test Runner. In general, SETUP Attribute and Teardown Attribute are used to prepare some must-have Objects, such as Database Connection, and more. The above program code demonstrates the method of using this Attribute.

ExpectedException Attributes Introduction

Sometimes, you want your program to produce some specific Exception under certain special conditions. To use the Unit Test to test whether the program is expected to generate Exception, you can use a try..catch program segment to catch (capture) this Exception, and then set a Boolean value to prove that Exception does happen. This method is feasible, but it is too spent. In fact, you should use this ExpectedException attribute to indicate which exception should be generated, as shown in the following example:

Namespace UnitTestingexamples

{

Using system;

Using nunit.framework;

[Testfixture] public class sometests {

[TEST]

[EXPECTEDEXCEPTION (TypeOperationException)] Public void test1 ()

{

// do something what thrtows an invalidopertyleException}

}

}

If the above program is executed, if exception occurs, and this Exception's Type is InvalidOperationException, this test will pass verification. If you expect your program code to generate multiple exception, you can also use multiple ExpectedException Attribute at a time. However, a Test Method should only test one thing, and test multiple functions at a time is not good, you should try to avoid it. In addition, this attribute does not check the relationship between INHEIRTANCE, that is, if your program code generated is the subclass (subclass) of InvalidOperationException, this TEST will not be verified. In short, when you use this Attribute, you have to specify which type (type information) of the expected Exception is. Ignore Attributes Introduction

You probably not often use it, but once it is needed, this Attribute is very convenient. You can use this attribute to indicate a Test Method, called Test Runner when executing, ignore this Method not to execute. The method of 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 temporary Comment Out a test method, you should consider using this attribute. This attribute allows you to keep your Test Method, in the execution of Test Runner, will also remind you that this slight Test Method exists.

Introduction to NUnit Assert Class

In addition to these of these mentioned above, NUNITs have an important Class, and you should know how to use it. This Class is Assert Class. Assert Class provides a range of Static Methods that allows you to verify that the results of the primary program are as expected. Assert Class replaces the old assertion class, the following is the method of this class:

AskERT.ISTRUE (BOOL);

AskERT.ISFALSE (BOOL);

Assert.isnull (BOOL);

Assert.isnotnull (BOOL);

AskERT.ASAME (Object, Object)

AskERT.Areequal (Object, Object);

AskERT.Arequal (int, int);

AskERT.AAt, Float, Float;

Assert.Arequal (double, double, double);

AskERT.FAIL ();

Examples of using this class are as follows:

Namespace UnitTeStingexamples {Using System; Using NUNIT.FRAMEWORK; [TestFixTure] public class sometests {[test] public void testlengthstring ()

{

// Should Return True

Bool Bresult1 = Class1.Checkpalindrome ("abccba");

AskERT.ISTRUE (BRESULT1);

// Should Return False

Bool BRESULT2 = Class1.checkpalindrome ("abcdba");

AskERT.ISFALSE (BRESULT2);

}

[TEST]

Public void testoddLengthString ()

{

// Should return true;

Assert.istrue (Class1.checkpalindrome);

// Should Return False

Assert.isfalse (Class1.Checkpalindrome)); "AbcDeba");

}

}

Perform your Tests

Ok, now we have discussed the basic steps and methods of writing Unit Tests, let us see how to do what you wrote. It is actually very simple. There are two Test Runner Applications in NUNIT: one is a window GUI program, one is a console XML program. You can freely choose what you like, basically there is no difference. If you want to use the window GUI Test Runner App, you only need to execute the program, then tell it what you want to perform the Assembly location. This contains Assembly, which you have written Test Methods is the Class Library (or Executable, *. DLL or * .exe) Assembly, which contains Test fixTures mentioned earlier. When you tell Test Runner where your Assembly is located, Test Runner will automatically load this ASEMBLY, then all Class and Test Methods are listed on the left column of the window. When you press the 'Run' button, you will automatically perform all listed Test Methods. You can also double the Test Class on the Double Click, or on a Test Method, which will automatically perform only the Class or the Method. Under the way, the window GUI TEST Runner is executed:

In some cases, especially if you want to join Unit Testing in your own build script, you probably use the GUI Test Runner. In this case of this automatic build script, you usually put your build's results on the web page, or write log file to save records, for program developers, managers or customers can learn more by checking this record. Happening. In this case, you can use NUnit 2.1 Console Test Runner Application. This Test Runner can be incorporated into the position of Assembly as a parameter, and its test execution result is an XML string. You can convert this XSLT or CSS to HTML, or other format you want. If you need this feature, check the NUNIT file for information on the Console Test Runner Application.

转载请注明原文地址:https://www.9cbs.com/read-31271.html

New Post(0)