springmvc使用junit4实现单元测试

如果读者对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);
    }

希望能给读者一下帮助

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值