单元测试
Unit Test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ActiveProfiles("dev")
@SpringApplicationConfiguration(
classes = { Application.class, MockServletContext.class }
)
@ImportResource("classpath:spring/applicationContext.xml")
public class AbstractTest {}
You will want to add a test for the endpoint you added, and Spring Test already provides some machinery for that, and it’s easy to include in your project. Add this to your build file’s list of dependencies:
testCompile("org.springframework.boot:spring-boot-starter-test")
If you are using Maven, add this to your list of dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Now write a simple unit test that mocks the servlet request and response through your endpoint:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class HelloControllerTest {
private MockMvc mvc;
@Autowired
private WebApplicationContext wac;
/**如果是配置启用整个Web环境
@Before
public void setUp() throws Exception {
this.mvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
**/
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void getHello() throws Exception {
mvc
.perform(
MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}
Note the use of the MockServletContext
to set up an empty WebApplicationContext
so the HelloController
can be created in the @Before
and passed toMockMvcBuilders.standaloneSetup()
. An alternative would be to create the full application context using the Application
class and @Autowired
the HelloController
into the test. The MockMvc
comes from Spring Test and allows you, via a set of convenient builder classes, to send HTTP requests into the DispatcherServlet
and make assertions about the result.