Scenario: In the project development to test the Springboot project a few DAO and service function is normal, initially in the Web project in the entry of elements, the workload is too large. Using this unit test greatly reduces the intensity of the work.
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 Springboot How to use JUnit in 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//@SpringApplicationConfiguration (classes = springbootsampleapplication. Class/ / Specify the application startup class for our Springboot project // because it is a Web project, JUnit needs to simulate ServletContext, So we need to add @webappconfiguration to our test class.
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:
Packageorg.springboot.sample;Import Staticorg.junit.Assert.assertArrayEquals;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;ImportOrg.springboot.sample.service.StudentService;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.test.SpringApplicationConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;Importorg.springframework.test.context.web.WebAppConfiguration;/** * * @authorTan Hongyu (365384722) * @mybloghttp://blog.csdn.net/catoop/* @create February 23, 2016*/@RunWith (Springjunit4classrunner.class) @SpringApplicationConfiguration (Classes= Springbootsampleapplication.class) @WebAppConfiguration Public classstudenttest {@AutowiredPrivateStudentservice Studentservice; @Test Public voidLikename () {assertarrayequals (Newobject[]{Studentservice.likename ("Xiaoming 2"). Size () > 0, Studentservice.likename ("Bad"). Size () > 0, Studentservice.likename ("Lily"). Size () > 0 }, Newobject[]{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:
Packageorg.springboot.sample;Import Staticorg.junit.Assert.assertTrue;Importjava.util.Arrays;Importjava.util.Collection;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.junit.runners.Parameterized;Importorg.junit.runners.Parameterized.Parameters; the @RunWith (parameterized.class) Public classParametertest {PrivateString name; Private Booleanresult; /*** The constructor parameter corresponds to the order of the values in the object array in the method @parameters annotated below *@paramname *@paramresult*/ PublicParametertest (String name,Booleanresult) { Super(); This. Name =name; This. result =result; } @Test Public voidTest () {asserttrue (Name.contains ("small") = =result); } /*** This method returns collection * *@return * @authorShanhy * @create February 26, 2016*/@Parameters Public StaticCollection<?>data () {//The order of the values in the Object array should correspond to the parameters of the constructor method parametertest above returnArrays.aslist (Newobject[][]{{"Xiaoming 2",true}, {"Bad",false}, {"Lily",false}, }); }}
4 Packaging 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 publicclass abcsuite { // class does not need to write code
5 API interface for testing HTTP with 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.
Here's a simple example.
Packageorg.springboot.sample;Import StaticOrg.junit.Assert.assertNotNull;Import StaticOrg.junit.Assert.assertThat;Import Staticorg.junit.Assert.assertTrue;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern;Importorg.hamcrest.Matchers;ImportOrg.junit.After;ImportOrg.junit.AfterClass;ImportOrg.junit.Before;ImportOrg.junit.BeforeClass;ImportOrg.junit.Ignore;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;ImportOrg.springframework.beans.factory.annotation.Value;Importorg.springframework.boot.test.SpringApplicationConfiguration;Importorg.springframework.boot.test.TestRestTemplate;Importorg.springframework.boot.test.WebIntegrationTest;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;ImportOrg.springframework.util.LinkedMultiValueMap;ImportOrg.springframework.util.MultiValueMap;Importorg.springframework.web.client.RestTemplate;/** * * @authorTan Hongyu (365384722) * @mybloghttp://blog.csdn.net/catoop/* @create February 23, 2016*/@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 8888 Public classHellocontrollertest {PrivateString Datereg; Privatepattern pattern; PrivateResttemplate template =Newtestresttemplate (); @Value ("${local.server.port}")//Injection Port number Private intPort; @Test Public voidtest3 () {String URL= "http://localhost:" +port+ "/myspringboot/hello/info"; Multivaluemap<string, object> map =NewLinkedmultivaluemap<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, matchers.containsstring ("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 8888 Public classhellocontrollertest {@Value ("${local.server.port}")//Injection Port number Private intPort; Private Static FinalLogger Logger = Loggerfactory.getlogger (Studentcontroller.class); @Rule//Note here that the use of @rule annotations must be public PublicOutputcapture capture =Newoutputcapture (); @Test Public voidtest4 () {System.out.println ("HelloWorld"); Logger.info ("Logo log will also be captured by capture test output"); Assertthat (Capture.tostring (), Matchers.containsstring ("World")); }}
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.
(EXT) Spring Boot junit Unit Test