Cainiao learning Java (21) -- how to better conduct unit tests -- JUnit

Source: Internet
Author: User

The importance of testing in the software declaration cycle should be clearly understood. There are many types of software testing. The testing methods include black box testing, white box testing, static testing, and dynamic testing. The software development process is divided: unit Testing, integration testing, validation testing, acceptance, regression, etc.


Among the many categories, unit tests are the most closely related to developers. For example, other types of tests are basically completed by dedicated testers, and only unit tests are completely completed by developers. So today we will talk about unit testing, why unit testing, and how to perform better unit testing.


What is unit testing?

Unit testing checks and verifies the minimum testable unit in the software. For example, we can test a class or a method in a class.


Why is unit testing required?

Why is unit testing required? To put it bluntly, what are the benefits of unit testing? In fact, the benefits of testing are nothing more than reducing bugs, improving code quality, and making code easy to maintain. For details about the advantages of unit testing, refer to the four articles summarized in Baidu Encyclopedia:


1. It is a verification behavior.
Every function in the program is tested to verify its correctness. It provides support for future development. Even after development, we can easily add features or change the program structure without worrying about the damage to important things in this process. It also guarantees code refactoring. In this way, we can improve the program more freely.


2. It is a design behavior.
Writing Unit Tests will let us observe and think from callers. In particular, writing test-first forces us to design programs that are easy to call and testable, which forces us to lift coupling in software.


3. It is a document writing activity.
Unit testing is an invaluable document that best shows how functions or classes are used. This document can be compiled, run, and kept up-to-date, always synchronized with the code.


4. It is regression.
Automated unit tests avoid code regression. After compilation, you can run tests anytime, anywhere.


How can we perform better unit tests?


Before discussing how to perform better unit tests, let's take a look at how we tested the code before.

Previously, the program was tested as follows:

public int add(int x,int y) {return x + y;}public static void main(String args[]) {int z = new Junit().add(2, 3);System.out.println(z);}

As shown above, when testing a method we have written, we usually use a main method to call the method we want to test and print the result. Now it seems that this method is very out, so many unit testing tools have emerged, such as JUnit and TestNG. They make unit tests very convenient and efficient. Let's talk about how to use JUnit for unit testing today.


We will create a new Java Project for demonstration. I will not go into details about how to create a Java Project here. If you connect to a Java Project, you are not suitable to read this article. After the project is created, right-click the "src" directory of the project, select new -- "JUnit Test Case, and enter the required information as follows:



Enter the package name and Class Name (New JUnit 4 Test), and click the "Browse" button at the bottom to select the class to be tested:



Manually enter the class we want to test, select the class, click "OK", return to the interface of the first image, and click "Next":



Select the method to be tested and click "Finish". The JUnit test instance is created. Then you can write the specific test:

Package com. tgb. junit. test; // import static org. junit. assert. *; import static org. hamcrest. matchers. *; import org. junit. test; import com. tgb. junit. junit; public class JUnitTest {@ Testpublic void testAdd () {int z = new Junit (). add (2, 3); assertThat (z, is (5) ;}@ Testpublic void testDivide () {int z = new Junit (). divide (4, 2); assertThat (z, is (2 ));}}

After writing it, right-click the class and select "Run As" -- "" JUnit Test ". The result indicates that the Test is successful:



At this point, there may be questions about the difference between JUnit and the main method testing?

First, the JUnit results are more intuitive. You can directly determine whether the test is successful based on the color of the status bar. You need to check the output result using the main method, then compare it with your expected results to know whether the test is successful. One sentence can intuitively illustrate this point-keeps the bar green to keeps the code clean. That is to say, as long as the status bar is green, your code is correct.

Second, JUnit makes it very convenient to run multiple tests at the same time. The following shows how to perform a multi-instance test:

First, we need to create another class to be tested, and then create a corresponding JUnit test instance. The procedure is omitted. Right-click the package of the test instance and choose "Run As" -- "Run deployments", As shown in;



Select the second item "Run all tests in the selected project, package or source folder", and then click "Run". the effect is as follows:



We can see that we have tested two classes in total with three methods. This convenient effect is more obvious when there are more test instances. As for running multiple tests in the main method, it is very troublesome to think about it. I will not describe it here.


In addition to testing these simple small programs, JUnit can also test Struts, JDBC, etc. Here we just use this small program for a brief introduction. This example uses hamcrest assertions instead of old ones, because hamcrest assertions are closer to natural language expressions and easier to understand.


The following three jar packages must be introduced to this instance:

Hamcrest-core-1.3.jar
Hamcrest-library-1.3.jar
Junit-4.10.jar


The following is a description of common hamcrest assertions:

If the value type is // n greater than 1 and less than 15, the test passes assertThat (n, allOf (greaterThan (1), lessThan (15 ))); // n greater than 16 or less than 8, the test passes assertThat (n, anyOf (greaterThan (16), lessThan (8); // n is any value, all tests passed assertThat (n, anything (); // The difference between d and 3.0 is ± 0. between 3, the test passes assertThat (d, closeTo (3.0, 0.3); // d is greater than or equal to 5.0, then the test passes assertThat (d, greaterThanOrEqualTo (5.0 )); // If d is less than or equal to 16.0, the test passes assertThat (d, lessThanOrEqualTo (16.0); If the value of character type // str is "tgb", the test passes assertThat (str, is ("tgb"); // If the str value is not "tgb", the test passes assertThat (str, not ("tgb ")); // If the str value contains "tgb", the test passes assertThat (str, containsString ("tgb"); // str ends with "tgb, the test passes assertThat (str, endsWith ("tgb"); // str starts with "tgb", then the test passes assertThat (str, startsWith ("tgb ")); // After str is case-insensitive and the value is "tgb", the test passes assertThat (str, struct toignoringcase ("tgb"); // After str ignores spaces, if the value is "tgb", the test passes assertThat (str, struct toignoringwhitespace ("tgb"); // n and nExpected are equal, then the test passes (between objects) assertThat (n, failed to (nExpected); collection type // map contains key-value pairs whose key and value are "tgb", the test passes assertThat (map, hasEntry ("tgb ", "tgb"); // if the list contains the "tgb" element, the test passes assertThat (iterable, hasItem ("tgb ")); // If map contains an element whose key is "tgb", the test passes assertThat (map, hasKey ("tgb ")); // If map contains an element whose value is "tgb", the test passes assertThat (map, hasValue ("tgb "));





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.