Spring Boot Unit Test

Source: Internet
Author: User

The old technology of JUnit is now being taken out, not for anything else, but in a way to illustrate its importance in the project.
In my own sense and experience, it should not be more than half the case that the JUnit use cases covered most of the business code in the project exactly as standard.

Just a while ago wrote some about Springboot's post, just now take junit out from a few aspects again, but also for some novice reference.

So let's talk about why we write test cases.
1. Can avoid the omission of test points, in order to better test, can improve the efficiency of testing
2. Can be tested automatically, can be tested before the project is packaged
3. Can be found in time because the code changes caused by the emergence of new problems, and timely resolution

Then this article from the following points to explain how to use JUNIT,JUNIT4 than 3 to facilitate a lot, the details can be understood, the main is version 4 of the method naming format no longer have requirements, no longer need to inherit testcase, everything is based on annotations implementation.

1. How to use JUnit in Springboot Web projects

Create a plain Java class that no longer needs to inherit the TestCase class in JUNIT4.
Because we are Web projects, we add annotations to the Java classes we create:

@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! @SpringApplicationConfiguration(classes = SpringBootSampleApplication.class) // 指定我们SpringBoot工程的Application启动类@WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。

You can then write a test method that uses @test annotation annotations.
In this class we can directly @autowired to inject the class instance we want to test, just like we normally develop.
Here's the full code:

Package org.springboot.sample;ImportStatic 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 Tan Hongyu (365384722) *@myblog http://blog.csdn.net/catoop/*@create February 23, 2016 */@RunWith (Springjunit4classrunner.Class@SpringApplicationConfiguration (classes = springbootsampleapplication.Class@WebAppConfigurationPublicClassstudenttest { @Autowired  Private Studentservice Studentservice;  @Test public void likeName () {assertarrayequals (new object[]{studentservice.likename ( " Xiao Ming 2 "). Size () > 0, Studentservice.likename (" bad "). Size () > Span class= "Hljs-number" >0, Studentservice.likename ( "Lily"). Size () > 0}, new object[]{true, false, true}); //asserttrue (Studentservice.likename ("Xiaoming 2"). Size () > 0);}}     

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

2. Introduction to JUnit Basic annotations

Executed once before all test methods, typically in which the overall initialization code is written
@BeforeClass

Executes once after all test methods, typically in which code is written to destroy and release resources
@AfterClass

Executed before each test method, typically used to initialize the method (for example, when we test other methods, the values shared with other test methods in the class have been changed, in order to ensure the validity of the test results, we will reset the data in the @before annotation method)
@Before

After each test method, what to do after the method execution is completed
@After

The test method executes more than 1000 milliseconds after the time-out, and the tests fail
@Test (timeout = 1000)

The test method expects the exception class to be obtained, and if the method execution does not throw the specified exception, the test fails
@Test (expected = exception.class)

This method is ignored when the test is executed, and the entire class is ignored if it is used to decorate the class
@Ignore ("Not Ready Yet")
@Test

@RunWith
There are many runner in JUnit, they are responsible for invoking your test code, each runner has its own special features, and you need to choose different runner to run your test code as needed.
If we are simply doing plain Java testing and do not involve the Spring Web project, you can omit the @runwith annotation so that the system automatically runs your code using the default runner.

3. Parametric testing

JUnit provides us with parameterized tests that require the use of @RunWith (Parameterized.class)
However, because JUnit uses @runwith to specify a runner, we need to use @runwith (springjunit4classrunner.class) to test our spring engineering methods in more cases, So we use Assertarrayequals to test the method in a variety of possibilities.

Here is a simple example of parametric testing:

Package org.springboot.sample;ImportStatic 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 classParametertest {PrivateString name; Private BooleanResult /** * The constructor method has parameters with the following @Parameters in the annotation method.The order of the values in the object array corresponds to * @param name * @paramResult */PublicParametertest (String Name, BooleanResult) {super (); this.name = name; this.result =Result } @Test Publicvoid Test () {Asserttrue (Name.contains ( "small") = = result); }/** * This method returns collection * * @return * @author shanhy * @create  2016 2 month  26th */@parameters public static collection<?> data () {//object the order of the values in the array note the above construction method parametertest parameters correspond to return arrays.aslist (New object[][]{{ "Xiaoming 2", true}, {false}, { "Lily",  False},}); }} 

4. Packing test
Under normal circumstances we have written 5 test classes, we need one to execute.
The package test is to add a new class and then configure the other test classes that we have written, and then run the class directly to achieve the same purpose of running 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 {    // 类中不需要编写代码} 

5. API interface for testing HTTP using JUnit
We can use this directly to test our REST API, if the internal unit testing requirements are not very strict, we guarantee the external API to fully test, because the API will invoke many internal methods, let it be considered as integration test it.

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.LinkedMultiValueMap;Import Org.springframework.util.MultiValueMap;Import Org.springframework.web.client.RestTemplate;/** * * @author Tan Hongyu (365384722) * @myblog http://blog.csdn.net/catoop/* @create February 23, 2016 */@Runwith (Springjunit4classrunner.Class) @Springapplicationconfiguration (classes =Springbootsampleapplication.Class@WebAppConfiguration//Use @webintegrationtest annotations to comment out the @webappconfigurationWebintegrationtest ("Server.port:0")Use 0 to indicate the port number is random, or you can specify a fixed port such as 8888PublicClasshellocontrollertest {PrivateString Datereg;PrivatePattern pattern;PrivateResttemplate template = newTestresttemplate (); @Value ("${local.server.port}")Injection port numberprivate int port; @Testpublic void Test3 () {String URL ="http://localhost:" +port+"/myspringboot/hello/info";multivaluemap<string, Object> Span class= "hljs-built_in" >map = new linkedmultivaluemap<String , object> (); map.add ( "name",  "Tom"); map.add ( "name1",  "Lily"); string result = Template.postforobject (URL, map,  String. class); system.out. println (Result), assertnotnull (Result), assertthat (result,  "Tom")); }} 

6. Capture output
Use Outputcapture to capture all output after the specified method begins execution, including the System.out output and log logs.
Outputcapture needs to use the @rule annotation, and the instantiated object needs to be decorated with the public, as in the following code:

@RunWith (Springjunit4classrunner.Class@SpringApplicationConfiguration (classes = springbootsampleapplication.Class@WebAppConfiguration//Use @webintegrationtest annotations to comment out the @webappconfiguration@WebIntegrationTest ("Server.port:0")Use 0 to indicate the port number is random, or you can specify a fixed port such as 8888PublicClass Hellocontrollertest {@Value ("${local.server.port}")//injection port number private int Port; private static final Logger Logger = Loggerfactory.getlogger (Studentcontroller. Class);  @Rule //here Note that using @rule annotations must be public public outputcapture capture = new outputcapture ();  @Test public void test4 () {System.out.println (   

Some of the assertion methods in the Assert class are very simple, and this article will not repeat them.

However, in the new version of JUnit, the Assertequals method has been deprecated, and it is recommended that we use Assertarrayequals, which is designed to allow us to test a method with several parameters for multiple probability tests.

Transferred from: https://yq.aliyun.com/articles/6925

Spring Boot Unit Test (RPM)

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.