@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(“file:src/test/java/spring-config.xml”)
@ActiveProfiles(“dev”)
@TransactionConfiguration(transactionManager = “transactionManager”, defaultRollback = true)
public abstract class BaseControllerTest {
protected MockMvc mvc;
@Autowired
private WebApplicationContext context;
//获取系统上下文
protected WebApplicationContext getCtx() {
return this.context;
}
//初始化方法
@Before
public void setup() throws SQLException {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
//封装返回结果
protected String getMockResultStr(MockHttpServletRequestBuilder requestBuilder) {
try {
MvcResult mvcResult = this.mockMvc
.perform(requestBuilder)
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
return response.getContentAsString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}