In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces how to use the unit testing tool NUnit in .NET development, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.
NUnit introduction
NUnit is a unit testing framework written specifically for .NET, it is a member of the xUnit system, and there are JUnit for Java and CPPUnit for C++ in the xUnit system. At the beginning, NUnit and most of the xUnit system did the same, just converting the Smalltalk or Java version, but after .NET 2.0 it added some unique practices. The official website of NUnit is http://www.nunit.org/, and the latest version is 2.6.2.
Download and install NUnit
Each version of NUnit provides two forms of download: installation files and installation-free methods, in * .msi format and * .zip format, respectively. The former needs to be installed to use, and will create some shortcuts and register NUnit's dll to GAC during installation, so that when writing NUnit test classes later, adding NUnit's dll is like adding .Net Framework's dll. If you download a file in zip format, no shortcuts are created and the dll is registered, and you need to manually specify the path to the dll of NUnit when writing the unit test class.
NUnit can be run in three ways: the command line and the graphical user interface. Take the NUnit2.5.10 installed on Zhou Gong's current computer as an example, the installation path is C:\ Program Files (x86)\ NUnit2.5.10, and there are three directories under it: bin, doc and samples. In the doc directory are the software documentation, and in the samples directory are some sample code. If you are in installation-free mode, you need to run the files in the bin directory to run NUnit. There are net-1.1 and net-2.0 folders in the bin directory, corresponding to different versions of .net.
Here is how to start NUnit in different ways:
Command line mode: run nunit-console.exe.
Graphical user interface mode: run nunit.exe.
Parallel mode: run pnunit-launcher.exe.
Note: the .net 2.0 version of NUnit is compiled using the / platform:anycpu parameter. We know that the result is that running on x86 systems will be compiled into 32-bit programs by JIT, and on x64 systems will be compiled into 64-bit programs by JIT. Testing 32-bit programs on x64 systems using NUnit can cause problems. To avoid this problem, you can use nunit-agent-x86.exe/nunit-x86.exe to test because / platform:x86 is used as the compilation parameter at compile time.
The following figure shows the GUI interface running NUnit:
Common Attribute tags for NUnit
These are properties that can be used as classes or methods, and they are direct or indirect subclasses of the System.Attribute class, as follows:
Category: used to classify tests. You can see the two tabs of Tests/Categories in the main interface, and if you mark the method with the Category attribute, you will see it in the Categories tab.
Combinatorial: for future testing, you need to test various possible combinations, such as the following code:
[Test, Combinatorial]
Public void MyTest (
[Values (1,2,3)] int x
[Values ("A", "B")] string s)
{
String value = x + s
Assert.Greater (2, value.Length)
}
Six situations are actually tested: MyTest (1, "A") / MyTest (1, "B") / MyTest (2, "A") / MyTest (2, "B") / MyTest (3, "A") / MyTest (3, "B").
Culture: set the locale for testing, which is useful for testing some language-sensitive scenarios, such as when DateTime.ToString () gets different strings in different locales.
Description: used to specify the descriptions for the test, which you will see in the XML file if you choose to generate the test results in the XML file.
ExpectedException: indicates that Exception will be thrown when the test is executed.
Explicit: if the class or method being tested uses this Attribute, the class or method must be selected on the interface before it is executed when using a NUnit test with GUI.
Explicit: ignore a test class or method.
Maxtime: the maximum number of milliseconds for the test method to execute. If the execution time of the program exceeds the specified value, the test will be considered to have failed.
Random: used to specify how parameters are randomly generated to test the method. Such as the following code:
[Test]
Public void TestDemo1 (
[Values (1,2,3)] int x
[Random (- 10pm 10pm 2)] int y)
{
Assert.Greater (x + y, 0)
}
The representation method TestDemo1 generates six tests, which are composed of six tests as the value of the parameter x and two random numbers y from-10 to 10.
Range: a method for specifying parameters, such as the following method:
[Test]
Public void TestDemo2 (
[Range (0,11,4)] int x)
{
Assert.AreEqual (x% 3jin0)
}
Indicates that it is incremented from 0, with a step size of 4 and no more than 11.
Repeat: the number of times the test will be repeated.
RequiresMTA: indicates that a multithreaded unit (multi-threaded apartment) is required for testing.
RequiresSTA: indicates that a single threaded unit (single-threaded apartment) is required for testing.
SetUp: initialization performed before each test method starts. Prior to NUnit 2.5, each class was required to have only one instance method with a SetUp attribute, but after NUnit 2.5, there was no restriction on the number of times and must be instance methods.
TearDown: contrary to the role of SetUp, it is a method that is executed after the end of each test method execution. Prior to NUnit 2.5, each class was required to have only one instance method with a SetUp attribute, but after NUnit 2.5, there was no restriction on the number of times and must be instance methods.
Test: used to mark methods that need to be tested, can only be used to mark instance methods before NUnit 2.5, and can be used to mark static methods after NUnit 2.5.
TestCase: the tagging method has parameters and provides the parameters needed for testing. Such as the following code:
[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)
}
Three tests will be performed, which is equivalent to:
[Test]
Public void DivideTest ()
{
Assert.AreEqual (4 meme 12 stroke 3)
}
[Test]
Public void DivideTest ()
{
Assert.AreEqual (6 meme 12 Universe 2)
}
[Test]
Public void DivideTest ()
{
Assert.AreEqual (3 memes 12 picks 4)
}
TestFixture: Mark that a class may have [Test] / [SetUp] / [TearDown] methods, but this class cannot be abstract.
TestFixtureSetUp: marks the method executed before all test methods in the class are executed. Prior to NUnit 2.5, this tag can only be used for one instance method in a class at most, but after NUnit 2.5, multiple methods can be marked, and not limited to instance methods can also be used for static methods.
TestFixtureTearDown: marks a method that executes after all test methods in the class have been executed. Prior to NUnit 2.5, this tag can only be used for one instance method in a class at most, but after NUnit 2.5, multiple methods can be marked, and not limited to instance methods can also be used for static methods.
Timeout: marks the maximum execution time of the method being tested. If the marked time is exceeded, the execution is canceled and the test is marked as a failure.
Values: tags as a series of parameters to the test method. There are usage examples in the previous code example.
NUnit's assertion (Assertions)
Assertions are at the core of all xUnit-based unit test series, and NUnit provides a wealth of assertions through the NUnit.Framework.Assert class. Specifically, NUnit provides a total of 11 categories of assertions, which are:
Equality Asserts: an assertion used to assert whether an object is equal, which is mainly represented by the overloading of two methods: Assert.AreEqual () and Assert.AreNotEqual (). The overloaded parameters include common basic numerical types (int/float/double, etc.) and reference types (represented by using object as a parameter).
Identity Asserts: an assertion used to determine whether an object of a reference type is the same reference and whether the assertion object exists in a collection, such as Assert.AreSame, Assert.AreNotSame, and Assert.Contains.
Condition Asserts: assertions for certain conditions, such as Assert.IsTrue, Assert.True, Assert.IsFalse, Assert.False, Assert.IsNull, Assert.Null, Assert.IsNotNull, Assert.NotNull, Assert.IsNaN, Assert.IsEmpty, and Assert.IsNotEmpty.
Comparisons Asserts: used for assertions between numeric values and types that implement the IComparable interface, such as Assert.Greater (greater than), Assert.GreaterOrEqual (greater than or equal to), Assert.Less (less than), Assert.LessOrEqual (less than or equal to).
Type Asserts: used to judge between types, such as whether an instance is a type or inherits from a type, such as Assert.IsInstanceOfType, Assert.IsNotInstanceOfType, Assert.IsAssignableFrom, Assert.IsNotAssignableFrom. Generic methods such as Assert.IsInstanceOf, Assert.IsNotInstanceOf, Assert.IsAssignableFrom, Assert.IsNotAssignableFrom have been added since NUnit 2.5. no, no, no.
Exception Asserts: assertions about exceptions, such as Assert.Throws/Assert.Throws, Assert.DoesNotThrow, Assert.Catch/Assert.Catch.
Utility Methods: for precise control of the testing process, there are four methods, namely: Assert.Pass, Assert.Fail, Assert.Ignore, Assert.Inconclusive. Assert.Pass is the opposite of Assert.Fail. The former means that the test will be terminated immediately and the test result will be marked as successful, while the latter will immediately terminate the test and mark the test result as a test failure. Assert.Ignore means to ignore the test, and this tag can be used to identify the test method or the test class.
StringAssert: for string assertions, the methods provided are StringAssert.Contains, StringAssert.StartsWith, StringAssert.EndsWith, StringAssert.AreEqualIgnoringCase, and StringAssert.IsMatch.
CollectionAssert: with respect to collection assertions, the methods provided are CollectionAssert.AllItemsAreInstancesOfType, CollectionAssert.AllItemsAreNotNull, CollectionAssert.AllItemsAreUnique, CollectionAssert.AreEqual, CollectionAssert.AreEquivalent, CollectionAssert.AreNotEqual, CollectionAssert.AreNotEquivalent, CollectionAssert.Contains, CollectionAssert.DoesNotContain, CollectionAssert.IsSubsetOf, CollectionAssert.IsNotSubsetOf, CollectionAssert.IsEmpty, CollectionAssert.IsNotEmpty, and CollectionAssert.IsOrdered.
FileAssert: for file-related assertions, two main methods are provided: FileAssert.AreEqual and FileAssert.AreNotEqual.
DirectoryAssert: assertions for folders. The methods provided are: DirectoryAssert.AreEqual, DirectoryAssert.AreNotEqual, DirectoryAssert.IsEmpty, DirectoryAssert.IsNotEmpty, DirectoryAssert.IsWithin, and DirectoryAssert.IsNotWithin.
The use of NUnit
The first time you open NUnit, there will be a blank interface, as shown in the following figure:
First we need to create a NUnit project. Clicking [File]-> [New Project] will bring up a dialog box to save the NUnit project, select the appropriate path and enter the appropriate name (note that the file suffix is .nunit), and then click the Save button to create a NUnit test project. In the future, we can open the project again.
At this point, the NUnit project does not contain any unit test cases, so we need to create a project that contains the test cases. Open Visual Studio to create a class library project (in a real project, the usual practice is to add a class library project to the current solution, so as to solve the dll reference problem), then we need to add a reference to NUnit, depending on whether we are installing or installation-free, usually we only need to add a reference to nunit.framework (the corresponding dll is unit.framework.dll).
The sample code used by the Duke of Zhou here is as follows:
Using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace UnitTestDemo {[TestFixture] public class NUnitTestDemo {private IList intList = new List (); [SetUp] [Category ("NA")] public void BeforeTest () {Console.WriteLine ("BeforeTest") } [TestFixtureSetUp] [Category ("NA")] public void BeforeAllTests () {Console.WriteLine ("BeforeAllTests");} [TearDown] [Category ("NA")] public void AfterTest () {Console.WriteLine ("AfterTest") } [TestFixtureTearDown] [Category ("NA")] public void AfterAllTests () {Console.WriteLine ("AfterAllTests");} [Test] [Category ("NA")] public void Test1 () {Console.WriteLine ("Test1") } [Test] [Category ("NA")] public void Test2 () {Console.WriteLine ("Test2");} [Test] public void TestFloat () {float value = 0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999; Console.WriteLine ("float value:" + value) Assert.AreEqual (value, 1f); Console.WriteLine ("TestFloat");} [Test] public void TestDouble () {double value = 0.999999999999999999999999d; Console.WriteLine ("double value:" + value); Assert.AreEqual (value, 1D); Console.WriteLine ("Test2") } [Test] public void TestDecimal () {decimal value = 0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 } [Test,Repeat (3)] public void TestIntList2 () {Assert.AreEqual (0, intList.Count);} [Test] public void TestIntList1 () {intList.Add (1); Assert.AreEqual (1, intList.Count) } [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) } [Test, Combinatorial,Description ("This is used for show Combinatorial")] public void MyTest ([Values (1,2,3)] int x, [Values ("A", "B")] string s) {string value = x + s; Assert.Greater (2, value.Length) } [Test] public void TestDemo1 ([Values (1, 2, 3)] int x, [Random (- 10LJ 10je 2)] int y) {Assert.Greater (x + y, 0) } [Test] public void TestDemo2 ([Range (0,11,4)] int x) {Assert.AreEqual (x% 3jue 0);}
Compile the project to generate dll. We can click [Project]-> [Add Assembly...] on the main interface of NUnit. To add the dll you just compiled. After loading successfully, the interface is as follows:
Click the [Run] button on the interface to start the test. Note that all testing methods are tested in this way. If we only want to test a few methods, we can check the check box in front of the aspect (by default, the check box does not appear, you need to click [Tools]-> [Setting] to open the settings interface, then click to find [Tree Display] under [GUI], check "Show CheckBoxes").
If we just want to test a method alone, it's even easier-just double-click that test method.
Sometimes we use some configuration information in the config file when testing, such as saving database connection string information and other configuration information in app.config/web.config. In order to enable NUnit testing to read the configuration information saved in app.config/web.config, we need to configure NUnit.
To demonstrate, we develop the following information:
Project name: UnitTestDemo
Project location: d:\ BlogCode\ UnitTestDemo\
Project compilation mode (Debug/Release): Debug
To demonstrate how to test the data saved in the config file, we wrote three test cases based on the code just now, as follows:
[Test] public void Test0_51CTOBlog () {StringAssert.AreEqualIgnoringCase (ConfigurationManager.AppSettings ["51ctoBlog"], "http://zhoufoxcn.blog.51cto.com");} [Test] public void Test0_CSDNBlog () {StringAssert.AreEqualIgnoringCase (ConfigurationManager.AppSettings [" CSDNBlog "]," http://blog.csdn.net/zhoufoxcn"); " } [Test] public void Test0_SinaWeiBo () {StringAssert.AreEqualIgnoringCase (ConfigurationManager.AppSettings ["SinaWeiBo"], "http://weibo.com/zhoufoxcn");}"
Also add the following data to the appSettings node of the app.config file:
If we don't make any settings on NUnit, we will get the wrong result, as shown in the following figure:
At this point, we can follow the steps below to configure, and click [Project]-[Edit...] Open the following interface:
Set ApplicationBase to the path of the current dll to be tested in the interface above. In this example: d:\ BlogCode\ UnitTestDemo\ bin\ Debug (note that if you copy the full path to the text box, NUnit will automatically change to the relative path). Because the current project is a class library project named UnitTestDemo, the name of the corresponding config file is UnitTestDemo.dll.config, and fill it in the text box behind the Configuration File Name. Then we click the [Run] button again and see that the test passes.
As a member of the xUnit system, NUnit does bring a lot of convenience to .net developers for unit testing. in the early days, we always used NUnit for unit testing. But there are also some shortcomings, such as: 1. JUnit in the xUnit system generates a new instance when testing each method, while in NUnit it is true that a TestFixture will generate only one instance, so that changes to the instance data to be included in the unit test class may affect other test methods (this does not happen if you generate one instance at a time, as in JUnit). two。 In the early days, most people thought that, like in JUnit, [SetUp] and [TearDown] would only be executed once before and after all tests, but in fact, they would be executed once before and after each test. In order to achieve the effect of [SetUp] and [TearDown] in JUnit, only TestFixtureSetUp and TestFixtureTearDown attributes can be added. In addition, there are some shortcomings and deficiencies.
Net development on the unit testing tool NUnit how to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.