Spring Boot Junit unit test

Source: Internet
Author: User

Spring Boot Junit unit test

The old Junit technology is nothing more than to mention, to some extent, to illustrate its importance in the project.
Based on my own feelings and experience, the Junit Use Cases Written completely in the project to cover most of the Business Code should not exceed half.

I wrote some posts about SpringBoot some time ago. Now I just want to take Junit out and discuss it from several aspects, which is a reference for some new users.

Let's briefly explain why we need to write test cases.
1. the test points can be avoided. In order to better test, the test efficiency can be improved.
2. Automatic Testing is supported. You can perform Test validation before project packaging.
3. You can promptly discover and solve new problems caused by code modification.

The following sections describe how to use Junit. Junit4 is much more convenient than 3. For details, you can understand it. The main reason is that the method naming format is no longer required in version 4, you no longer need to inherit from TestCase. Everything is implemented based on annotations.

1. How to Use Junit in the SpringBoot Web Project

Create a common Java class. In Junit4, you no longer need to inherit the TestCase class.
Because we are a Web project, add annotations to the created Java class:

@ RunWith (SpringJUnit4ClassRunner. class) // SpringJUnit support, which introduces Spring-Test framework support! @ SpringApplicationConfiguration (classes = SpringBootSampleApplication. class) // specify the Application startup class @ WebAppConfiguration of our SpringBoot project // since it is a Web project, Junit needs to simulate ServletContext, so we need to add @ WebAppConfiguration to our test class.

Next, you can compile the Test method, and use the @ Test annotation to mark the Test method.
In this class, we can directly inject the class instance we want to test with @ Autowired, just like normal development.
The complete code is as follows:

Package org. springboot. sample; import static org. junit. assert. assertArrayEquals; import org. junit. test; import org. junit. runner. runWith; import org. springboot. sample. service. studentService; import org. springframework. beans. factory. annotation. autowired; import org. springframework. boot. test. springApplicationConfiguration; import org. springframework. test. context. junit4.SpringJUnit4ClassRunner; import org. springframework. test. context. web. webAppConfiguration;/***** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create February 23, 2016 */@ RunWith (SpringJUnit4ClassRunner. class) @ SpringApplicationConfiguration (classes = SpringBootSampleApplication. class) @ WebAppConfigurationpublic class StudentTest {@ Autowired private StudentService studentService; @ Test public void likeName () {assertArrayEquals (new Object [] {studentService. likeName ("James 2 "). size ()> 0, studentService. likeName ("bad "). size ()> 0, studentService. likeName ("Lili "). size ()> 0}, new Object [] {true, false, true}); // assertTrue (studentService. likeName ("James 2 "). size ()> 0 );}}

Next, you need to add countless test classes and write countless test methods to ensure the effectiveness of our developed programs.

2. introduction to basic Junit annotations

// Execute the entire initialization code once before all test methods.
@ BeforeClass

// Execute the command once after all test methods. Generally, write the code for destroying and releasing resources.
@ AfterClass

// Execute before each test method, which is generally used to initialize the method (for example, when we test another method, the value shared with other test methods in the class has been changed, to ensure the effectiveness of the test results, we reset the data in the @ Before annotation method)
@ Before

// Execute each test method and what to do after the method is executed
@ After

// If the test method times out after it is executed for more than 1000 milliseconds, the test will fail.
@ Test (timeout = 1000)

// The expected exception class of the test method. If the method execution does not throw the specified exception, the test fails.
@ Test (expected = Exception. class)

// This method is ignored during the test. If this method is used to modify the class, the entire class is ignored.
@ Ignore ("not ready yet ")
@ Test

@ RunWith
There are many Runner in JUnit who are responsible for calling your test code. Each Runner has its own special functions. You need to select different Runner as needed to run your test code.
If we just perform a simple Java test and do not involve Spring Web projects, you can omit the @ RunWith annotation so that the system will automatically use the default Runner to run your code.

3. parameterized Test

@ RunWith (Parameterized. class) is required for the parameter tests provided by Junit)
However, since Junit uses @ RunWith to specify a Runner, we need to use @ RunWith (SpringJUnit4ClassRunner in more cases. class) to test our Spring engineering method, so we can use assertArrayEquals to test multiple possibilities of the method.

The following is a simple example of parametric testing:

Package org. springboot. sample; import static org. junit. assert. assertTrue; import java. util. arrays; import java. util. collection; import org. junit. test; import org. junit. runner. runWith; import org. junit. runners. parameterized; import org. junit. runners. parameterized. parameters; @ RunWith (Parameterized. class) public class ParameterTest {private String name; private boolean result; /*** the constructor Parameters correspond to the order of the values in the Object array in the @ Parameters annotation Method * @ param name * @ param result */public ParameterTest (String name, boolean result) {super (); this. name = name; this. result = result;} @ Test public void test () {assertTrue (name. contains ("small") = result);}/*** this method returns Collection ** @ return * @ author SHANHY * @ create February 26, 2016 */@ Parameters public static Collection
  Data () {// The Order of the values in the Object array must be consistent with the return Arrays parameter of the preceding constructor ParameterTest. asList (new Object [] [] {"James 2", true}, {"bad", false },{ "Lily", false },});}}
4. Packaging Test

Under normal circumstances, we have written five test classes, and we need to execute them one by one.
The package test is to add a class, configure the other test classes we have written together, and directly run this class to run several other tests at the same time.

The Code is as follows:

@ RunWith (Suite. class) @ SuiteClasses ({ATest. class, BTest. class, CTest. class}) public class ABCSuite {// No code needs to be written in the class}
5. Use Junit to test the HTTP API

We can directly use this to test our Rest API. If the internal unit test requirements are not very strict, we can ensure that the external API can be fully tested, because the API will call many internal methods, consider it as an integrated test.

The following is a simple example:

Package org. springboot. sample; import static org. junit. assert. assertNotNull; import static org. junit. assert. assertThat; import static org. junit. assert. assertTrue; import java. util. regex. matcher; import java. util. regex. pattern; import org. hamcrest. matchers; import org. junit. after; import org. junit. afterClass; import org. junit. before; import org. junit. beforeClass; import org. junit. ignore; import org. junit. test; import org. junit. runner. runWith; import org. springframework. beans. factory. annotation. value; import org. springframework. boot. test. springApplicationConfiguration; import org. springframework. boot. test. testRestTemplate; import org. springframework. boot. test. webIntegrationTest; import org. springframework. test. context. junit4.SpringJUnit4ClassRunner; import org. springframework. util. extends multivaluemap; import org. springframework. util. multiValueMap; import org. springframework. web. client. restTemplate;/***** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create February 23, 2016 */@ RunWith (SpringJUnit4ClassRunner. class) @ SpringApplicationConfiguration (classes = SpringBootSampleApplication. class) [email protected] // use the @ WebIntegrationTest annotation to comment out @ WebAppConfiguration @ WebIntegrationTest ("server. port: 0 ") // use 0 to indicate random port numbers. You can also specify public class HelloControllerTest {private String dateReg; private Pattern pattern for a fixed port such as 8888; private RestTemplate template = new TestRestTemplate (); @ Value ("$ {local. server. port} ") // inject the port number private int port; @ Test public void test3 () {String url =" http: // localhost: "+ port +"/myspringboot/hello/info "; MultiValueMap
  
   
Map = new LinkedMultiValueMap
   
    
(); Map. add ("name", "Tom"); map. add ("name1", "Lily"); String result = template. postForObject (url, map, String. class); System. out. println (result); assertNotNull (result); assertThat (result, Matchers. containsString ("Tom "));}}
   
  
6. Capture output

Use OutputCapture to capture all output after the specified method starts execution, including System. out output and Log.
OutputCapture requires @ Rule annotation, And the instantiated object needs to be modified using public. The following code:

@ RunWith (SpringJUnit4ClassRunner. class) @ SpringApplicationConfiguration (classes = SpringBootSampleApplication. class) [email protected] // use the @ WebIntegrationTest annotation to comment out @ WebAppConfiguration @ WebIntegrationTest ("server. port: 0 ") // use 0 to indicate random port numbers. You can also specify public class HelloControllerTest {@ Value (" $ {local. server. port} ") // injection port number private int port; private static final Logger logger = LoggerFactory. getLogger (StudentController. class); @ Rule // note that the @ Rule annotation must use public OutputCapture capture = new OutputCapture (); @ Test public void test4 () {System. out. println ("HelloWorld"); logger.info ("the logo log will also be captured by the capture test output"); assertThat (capture. toString (), Matchers. containsString ("World "));}}

Some Assert methods in the Assert class are simple and will not be repeated here.

However, in the new Junit version, the assertEquals method has been deprecated. We recommend that you use assertArrayEquals to test multiple possibilities by passing several parameters when testing a method.

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.