SSM项目Junit单元测试

本文介绍了如何在SSM项目中使用Junit进行单元测试,避免了每次启动容器测试数据层和业务层的繁琐过程。通过示例代码展示Junit在测试中的便捷性,鼓励读者尝试并给予点赞。

项目搭建就不重复说了,有不明白的请参考 Maven+Eclipse(STS)搭建SSM项目笔记: https://www.jianshu.com/p/ca0e929c180a

使用SSM项目测试问题,每次启动容器测试数据层,业务层代码有点麻烦。使用Junit单元测试可以解决每次测试数据层,业务层,控制层的代码测试。直接上代码。

package com.ssm.test;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;


/**
* *测试
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")  
// 只是测试数据层只需要指定mybatis配置文件即可
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml"})
// 业务层测试指定配置文件
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml", "classpath:config/spring/springmvc.xml" })
// 可以使用统配符号 *
@ContextConfiguration({ "classpath:config/spring/*.xml"})
// 事务
@Transactional(transactionManager = "transactionManager")
// 测试结束后事物是否回滚;默认true;
@Rollback(value = false) 
public class AppTest {
    private static final Logger log = Logger.getLogger(AppTest.class);
    @Autowired  
    private WebApplicationContext wac;  
    private MockMvc mockMvc;  
    @Before  
    public void setUp() {  
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  
    }  

    @Test
    public void helloControllerTest() throws Exception {
        log.info("==========访问http://localhost:8080/ssm/hello/index=======================");
        String contentAsString = mockMvc.perform(MockMvcRequestBuilders.get("/hello/index"))
                                        .andReturn()
                                        .getResponse()
                                        .getContentAsString();
        log.info(contentAsString);
    } 
    
    
    @Resource
    private UserMapper userMapper;
    @Test
    public void userMapperSelectByIdTest() {
        log.info("==========测试数据层使用=======================");
        User user = userMapper.selectById(1);
        log.info(user);
    } 
}

是不是很方便呀!如果帮到了你,麻烦老铁点赞!谢谢各位。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值