配置測(cè)試環(huán)境
1.在 pom.xml中導(dǎo)入 spring-test 模塊逮京。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
2.如果使用的是Spring4進(jìn)行測(cè)試余耽,需要 servlet3.0的支持。
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
測(cè)試類
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MvcTest {
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
@Before
public void init() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testPage() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/messages").param("pn", "5"))
.andReturn();
MockHttpServletRequest request = result.getRequest();
PageInfo pi = (PageInfo) request.getAttribute("pageInfo");
System.out.println(pi);
}
}
配置注解:
- @RunWith(SpringJUnit4ClassRunner.class) 測(cè)試運(yùn)行于Spring測(cè)試環(huán)境笋额。
- @ContextConfiguration 加載Spring的配置文件冯袍。
- @WebAppConfiguration 表明應(yīng)該為測(cè)試加載WebApplicationContext,必須與@ContextConfiguration一起使用。
- @Before 編寫(xiě)測(cè)試方法執(zhí)行前的邏輯苍鲜,可以初始化MockMVC實(shí)例思灰。
- @Test 標(biāo)明實(shí)際測(cè)試方法,建議每個(gè)Controller對(duì)應(yīng)一個(gè)測(cè)試類混滔。