Unit Testing is supported in various languages during development. in C #, we use nunit for testing. Official Website: www.nunit.org. The latest stable version is nunit2.5. You can download and install the MSI file, developers of vs2005 can use nunit2.48. As for the 2.5 support, there is no research.
Add reference nunit. Framework in vs2005. First, we will compile a class before testing. This class (the original class) will be used later to demonstrate how to perform unit testing.
Code
1 class Calculator
2 {
3 Public int add (int A, int B)
4 {
5 return (A + B );
6}
7
8 Public int minus (int A, int B)
9 {
10 return (a-B );
11}
12
13 public int multiply (int A, int B)
14 {
15 return (A * B );
16}
17
18 public int divide (int A, int B)
19 {
20 return (A/B );
21}
22
23 static void main (string [] ARGs)
24 {
25}
26}
With the original class above, we will start to compile the test class, which has some instructions on the test class: The naming rules of the test class have certain requirements. Generally, test is added after the name of the original class, in this way, the name of the above test class should be calculatortest.
Code
1 [testfixture]
2 public class calculatortest
3 {
4 [test]
5 Public void testadd ()
6 {
7 calculator c = new calculator ();
8
9 int result = C. Add (1, 3 );
10
11 assert. areequal (4, result );
12
13}
14}
At the same time, you should note that the test method has no return type, no parameters, and the modifier is public. Note that the attribute [testfixtrue] identifies this class as a test class and the [test] identifies the test method, the above only implements the Add addition test and starts nunit2.48 (I used 2.48). The specific steps are: file-> openobject-> Find the executable file calculator.exe of the class, and nunit automatically loads the test classes and test methods in it, click Run. When we see a green one, the test passes (keep the bar green to keep the code clean ). In this way, we have learned how to get started with the test. You can try to test the remaining methods by yourself. Pay special attention to the divide method test to see what will happen?