A dot eyeball.
Testing is the key to ensuring software quality. In the previous tutorial, I covered simple testing. Now I’m going to do some tests related to Spring MVC, mainly involving controller testing.
To test a Web project without usually starting the project, we need some servlet-related mock objects, such as MockMVC, MockHttpServletRequest, MockHttpServletResponse, MockHttpSession, etc.
In Spring, we use @webAppConfiguration to specify that the loaded ApplicationContext is a WebAppConfiguration.
The following example uses JUnit and The Spring TestContext Framework to demonstrate testing the normal page steering controller and RestController, respectively.
Examples:
1. Test dependencies
<! -- spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-framework.version}</version> <scope>test</scope> </dependency> <! -- dependency> <groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>Copy the code
Code explanation:
Here
indicates that these packages will survive the test cycle, which means that we will not include these JAR packages when we release them.
test
2. Demo Service:
Add the DemoService class under SRC /main/ Java as follows:
package org.light4j.springMvc4.service; import org.springframework.stereotype.Service; @Service public class DemoService { public String saySomething(){ return "hello"; }}Copy the code
Test cases
New TestControllerIntegrationTests under SRC/test/Java classes, the code is as follows:
package org.light4j.springMvc4.web; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.light4j.springMvc4.MyMvcConfig; import org.light4j.springMvc4.service.DemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {MyMvcConfig.class}) @ WebAppConfiguration (" SRC/main/resources ") / / (1) the public class TestControllerIntegrationTests {private MockMvc MockMvc; //② @autoWired private DemoService DemoService; / / (3) the @autowired WebApplicationContext wac. / / (4) the @autowired MockHttpSession session; / / (5) the @autowired MockHttpServletRequest request; / / 6 @ Before / / 7 public void setup () {mockMvc = MockMvcBuilders. WebAppContextSetup (enclosing wac). The build (); } @test public void testNormalController() throws Exception{mockMvc. Perform (get("/normal")) //⑧ AndExpect (the status (). IsOk ()) / / pet-name ruby andExpect (view (). The name (" page ")) / / attending .andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))//11 .andExpect(model().attribute("msg", demoService.saySomething())); //12 } @Test public void testRestController() throws Exception{ mockMvc.perform(get("/testRest")) //13 .andExpect(status().isOk()) .andExpect(content().contentType("text/plain; charset=UTF-8"))//14 .andExpect(content().string(demoService.saySomething())); / / 15}}Copy the code
Code explanation:
The @webAppConfiguration annotation on a class declares that the loaded ApplicationContext is a WebApplicationContext. Its properties specify the location of the Web resource, which is SRC /main/webapp by default and SRC /main/resource in this example. (2) MockMvc MVC simulation object, through MockMvcBuilders webAppContextSetup (enclosing wac). The build () to initialize. ③ You can inject Spring beans into test cases. ④ You can inject WebApplicationContext. ⑤ The HTTP session that can be injected into the simulation is only used for demonstration. ⑥ HTTP request can be injected to simulate, here only for demonstration, not used. ⑦ @Before Initialization work Before the test begins. ⑧ Simulate get requests to /normal. ⑨ The expected control return status is 200. ⑩ The expected view name is Page. 11 expectations to the real path to/WEB page – INF/classes/views/page. The JSP. 12 The expected value in model is demoservice.saySomething () returns hello. 13. Simulate a GET request to /testRest. 14 The media type of the expected return value is text/plain. Charset = utf-8. 15 The expected return value of demoservice.saySomething () is hello.
At this point, run the test,The effect is shown below:
4. Write common controllers
Add the NormalController class under SRC /main/ Java as follows:
package org.light4j.springMvc4.web; import org.light4j.springMvc4.service.DemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class NormalController { @Autowired DemoService demoService; @RequestMapping("/normal") public String testPage(Model model){ model.addAttribute("msg", demoService.saySomething()); return "page"; }}Copy the code
5. Write a demo page for a common controller
Create a new page.jsp under SRC /main/resources/view
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Test page</title> </head> <body> <pre> Welcome to Spring MVC world </pre> </body> </html>Copy the code
6. Write the RestController controller
Add the RestController class to SRC /main/ Java as follows:
package org.light4j.springMvc4.web;
import org.light4j.springMvc4.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RestController
public class MyRestController {
@Autowired
DemoService demoService;
@RequestMapping(value = "/testRest" ,produces="text/plain;charset=UTF-8")
public @ResponseBody String testRest(){
return demoService.saySomething();
}
}Copy the code
7. Run the tests
The effect is shown below:
Three. Source code examples:
Github Address: Click to view code cloud address: click to view
exceptional
Welcome to follow the life designer’s wechat public account
longjiazuoA