I. Overview
Basic knowledge, reference: https://www.cnblogs.com/ysw-go/p/5447056.html
Second, unit test of Springboot
1. Getting Started test class
The most important thing is not to forget the dependencies on the class, and the @test on the methods in the class (the underlying is JUnit)
PackageCom.example.demo;ImportCom.example.demo.service.GirlService;ImportOrg.junit.Assert;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.test.context.junit4.SpringRunner;/*** Girlservice Test class * *@authorZCC on 2018/2/9 **/@RunWith (Springrunner.class) @SpringBootTest Public classgirlservicetest {@AutowiredPrivateGirlservice Girlservice; @Test Public voidfindonetest () {assert.assertequals (NewInteger (4), Girlservice.findone (). Getage ()); }}
In this way, you can see the relevant results:
In order to be taller, please do not use the small white sout again, use the assertion more.
2. Automatically generate test classes using idea
For example, to test the FindOne in the service above, by right-clicking->goto->test on the method
API Unit test for 3.controller
Similarly, right-clicking on the method, Goto->test, gets the test class
PackageCom.example.demo.controller;Importcom.example.demo.SpringbootDemoApplicationTests;Importorg.junit.Test;Importorg.springframework.beans.factory.annotation.Autowired;ImportORG.SPRINGFRAMEWORK.BOOT.TEST.AUTOCONFIGURE.WEB.SERVLET.AUTOCONFIGUREMOCKMVC;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;Import Staticorg.junit.assert.*; @AutoConfigureMockMvc Public classGirlcontrollertestextendsspringbootdemoapplicationtests {@AutowiredPrivateMOCKMVC MVC; @Test Public voidGetList ()throwsException {//Test Status CodeMvc.perform (Mockmvcrequestbuilders.get ("/girls") . Andexpect (Mockmvcresultmatchers.status (). IsOk ()); }}
One of the uses of unit testing is that the package is automatically run unit tests and will give the test results, which will be reported error! when failed
There are other test options, such as testing. Content.string ("ABC" to test the return content), complete API, reference: here
Springboot-web Advanced (four)--unit test