如果读者对junit4单元测试框架,不熟悉的话可以先看一下以下博客
http://blog.csdn.net/afeilxc/article/details/6218908
因为这里是主要分析spring是如何集成junit4进行测试的,我使用的IDEA开发,项目管理使用的是maven,如果不知如何直接生成junit测试类可以查看如下博客:
http://blog.csdn.net/czd3355/article/details/53572989
我这里直接把我的一个springmvc测试类的代码copy出来,里面有相应的注释
/**
*测试
*/
@RunWith(SpringJUnit4ClassRunner.class)//此处调用Spring单元测试类
@WebAppConfiguration //调用javaWEB的组件,比如自动注入
@ContextConfiguration(locations = {"classpath*:/applicationContext.xml"})//加载spring容器
//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否
//@TransactionConfiguration( transactionManager = "transactionManager",defaultRollback = true)
//@Transactional
public class UserLoginControllerTest {
@Resource
private UserLoginController userLoginController;
@Autowired
private WebApplicationContext wac;
//Spring提供的测试类
private MockMvc mockMvc;
/**
* 初始化SpringmvcController类测试环境
*/
@Before
public void setup(){
//加载web容器上下文 mockMvc=MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testGetTrdSession() throws Exception {
//resultAction是用来模拟客户端请求
ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("/itarget/user/getTrdSession")
.accept(MediaType.APPLICATION_JSON).param("jsCode","031EftpO11IN361cMDsO1cvbpO1EftpI"));
//MvcResult是获得服务器的Response内容。
MvcResult mvcResult = resultActions.andReturn();
String result = mvcResult.getResponse().getContentAsString();
System.out.println("*******:" + result);
}
希望能给读者一下帮助