A test class consists of the following two annotations:
@RunWith (Springrunner. Class) @SpringBootTest
The interface can be injected directly into the test class:
@ResourceMyServerMgr Myservermgr;
Adding @test to a method means that it is a test method:
@Test Public void = myservermgr.query (); Log.info ("Test query result is {}.") // use assertion to determine the result assertequals (result, "query result");}
The behavior of the test method before and after execution can be expressed by means of @before and @after annotation adornments.
@Before Public void throws Exception {log.info ("before setUp.") );} @Afterpublicvoidthrows Exception {log.info (' after TearDown. ') );}
At this point a simple unit test is complete. Spring mock MVC: Simulates a test controller in a servlet container. The following section describes how to test the spring Controller API. The Controller test class requires additional @webappconfiguration annotations:
@RunWith (Springrunner. Class) @SpringBootTest @webappconfiguration
You need to inject webapplicationcontext into the test class:
@Resource Private Webapplicationcontext Webapplicationcontext;
You need to send a rest request using MOCKMVC impersonation, so you need to define the MOCKMVC variable and initialize it before the test method executes:
Private Mockmvc Mockmvc; Public void throws Exception {log.info ("Set Mockmvc"= Mockmvcbuilders.webappcontextsetup ( Webapplicationcontext). Build (); // Mockmvc = Mockmvcbuilders.standalonesetup (webapplicationcontext). build (); }
It is necessary to note that Mock MVC is constructed in two ways:
Standalonesetup: Manually created and configured controllers.
Webappcontextsetup: Constructs mock MVC according to the spring application context.
We use the webappcontextsetup approach. To declare a test method using @test annotations:
@Test Public void throws Exception {mockmvc.perform (Get ("/myapp")). Andexpect (Status (). IsOk ()). Andexpect (Content (). String ( "Query result");}
To summarize:
1, need to be familiar with and master @runwith (Springrunner.class), @SpringBootTest, @Before, @After, @Test the use of several annotations. 2, the difference between the test server interface and the test controller is that the controller needs an additional load context and initializes the MOCKMVC, and sends a rest request through the MOCKMVC simulation to determine whether the result is correct by the assertion.
Spring Boot Unit Test