When talking about unit testing, people who have just graduated or have not graduated may mostly stay in the definition stage described in the textbook. It is estimated that there will not be many people who will remember the definition. Our education is always so comforting ". So what is unit test? We don't care about the specific scientific definition. In fact, every person who writes code performs unit tests at all times, unless you never verify whether the code you write can achieve the expected purpose, instead, you can simply finish writing the script without even running it.
The straightforward aspect of unit testing is to verify whether a piece of code is correctly written. It may be a class, a function, or even a loop. For the convenience of testing, we usually directly test the code in the ready runable code. We can see that the console outputs the expected results or throws an exception. But after entering the company, such a test method is extremely unprofessional and it is not easy to reproduce the test environment. You may need to write a test class, call the code unit you want to test, and then perform the test. However, it is quite troublesome to create a new class and write test cases each time.
With so much said, welfare is coming. Unit test tool-JUnit. Assists us with unit testing, which provides a lot of convenience. The following describes how to use JUnit for unit testing in eclipse.
Suppose we have compiled a calculator to provide some simple calculator functions. The Code is as follows, intentionally leaving some bugs.
1 package Org. logback. test; 2 3 Public class calculator {4 5 Private Static int result; 6 // static variable, used to store the running result 7 8 Public void add (int n) {9 10 result = Result + N; 11 12} 13 14 public void substract (int n) {15 16 Result = Result-1; // BUG: correct should be result = result-n17 18} 19 20 public void multiply (int n) {21 22} // This method has not implemented 23 24 public void divide (int n) {25 26 result = Result/N; 27 28} 29 30 public void square (int n) {31 32 result = N * N; 33 34} 35 36 Public void squareroot (int n) {37 38 for (;); // BUG: endless loop 39 40} 41 42 Public void clear () {// clear the result 43 44 result = 0; 45 46} 47 48 Public int getresult () {49 50 return result; 51 52} 53}
The unit test should be performed on this class to the extent of development. The method is very simple. First, right-click the project name to which the class belongs and choose Properties.
In the pop-up Properties window, select Java build path on the left side, then select the libraries tab card on the right side, and finally select Add library.
In the pop-up add library window, select JUnit and click Next, select junit4 from the drop-down menu, and click Finish.
In this way, JUnit is introduced to libraries of the project and click OK. Right-click the class to be tested and choose new> JUnit test case.
In the pop-up new window, set as follows. The specific meaning will be explained later.
Here you can choose to place the test class in a dedicated test package and give the test class an obvious name. Select next and enter.
Select the method to be tested. If we only test the addition, subtraction, multiplication, division, and division methods, select the corresponding four methods and click Finish. A test class is automatically generated, but we still need to modify the class to the following code.
1 package Org. logback. test; 2 3 Import static Org. JUnit. assert. *; 4 5 import Org. JUnit. after; 6 Import Org. JUnit. afterclass; 7 Import Org. JUnit. before; 8 Import Org. JUnit. beforeclass; 9 Import Org. JUnit. ignore; 10 Import Org. JUnit. test; 11 12 public class calculatortest {13 14 Private Static calculator example = new calculator (); 15 16 @ before // Method 17 Public void setup () throws exception {18 example before each test method is executed. clear (); 19} 20 21 @ After // Method 22 public void setdown () {23 system. out. println ("over"); 24} 25 26 @ beforeclass // method called when the class is loaded, which must be public and static. Only 27 public static void start () is called once () {28 system. out. println ("start class"); 29} 30 31 @ afterclass // The method called at the end of the class, which must be public and static, only call 32 public static void destory () {33 system. out. println ("destory class"); 34} 35 36 @ test37 public void testadd () {38 example. add (2); 39 example. add (3); 40 assertequals (5, example. getresult (); 41} 42 43 @ test44 public void testsubstract () {45 example. add (10); 46 example. substract (2); 47 assertequals (8, example. getresult (); 48} 49 50 @ ignore // Test 51 @ test52 public void testmultiply () {53 fail ("not yet implemented") is ignored because this method is not implemented for the moment "); 54} 55 56 @ test57 public void testdivide () {58 example. add (8); 59 example. divide (2); 60 assertequals (4, example. getresult (); 61} 62 63 @ test (timeout = 1000) // set the time limit, in milliseconds. Timeout is counted as test failure 64 public void testsquareroot () {65 example. squareroot (4); 66 assertequals (2, example. getresult (); 67} 68 69 @ test (expected = arithmeticexception. class) // test whether the exception is thrown as scheduled. 70 public void dividebyzero () {71 example. divide (0); // The divisor is 0. if an exception is thrown correctly, the test passes. Otherwise, the test fails. 72} 73}
Each method is annotated to indicate its specific purpose.
To test the calculator function, you must first create a corresponding instance, as shown in line 14. There are a lot of things starting with @ in the Code. Below is a brief introduction. Annotation started with @ is a feature introduced by jdk1.5. The meanings of commonly used annotations in JUnit are described as follows:
@ Test: The annotation is a test method, which includes the attribute timeout (used to set the time limit, in milliseconds. If the time limit is exceeded, the test is returned as a failure), expected (set the exception that should be thrown here. If this exception is thrown, the test is successful; otherwise, the test fails)
@ Before: the labeled method is executed once before each test method is executed.
@ After: The labeled method is executed once after each test method is executed.
@ Beforeclass: The annotation method is executed once during class loading, and only once. This method must be public and static.
@ Afterclass: The annotation method is executed once when the class is destroyed. The method must be public or static.
@ Ignore indicates that the test is ignored because the method to be tested is not implemented.
@ Parameters: the annotation is used to define a set of test data. It is generally used to pass multiple groups of test data to a test method.
The preceding annotations are used for annotation. The following describes two annotation classes:
@ Runwith (classname. Class) specifies the runner used in this test. If not set, the default runner is used, as in the previous example.
@ Suite. suiteclasses ({
Testclassname1.class,
Testclassname2.class,
...
}) Packaging test, sometimes there are many test classes in the same class. It is too troublesome to run the test classes one by one. In this way, all the test classes to be run are run together. An example is provided later in this article.
After the annotation is introduced, let's take a look at the assertequals function used in the test method. This method has two parameters: the first is the expected value, and the second is the result passed to the method to compare whether the results after the method processing are consistent with the expected results, therefore, the system returns whether the test is successful or fails.
Perform the test with the previous Code as follows:
Right-click the class and choose run as> JUnit test.
The result shown in the left-side JUnit tag is as follows:
Indicates that a test method fails to be returned. The six test methods are listed. blue X indicates that the expected results are different from the actual results, and red X indicates that the limit is exceeded (this indicates that the time has timed out, because there is an endless loop in the method called by the test method), Green √ indicates that the test method is successful, and gray/indicates that the test method is ignored. When you click the corresponding method name in the list, the failure trace below will provide an error message.
The preceding example does not require multiple groups of data. OK, so many today! Continue in the next day ~