idea + Maven + Spring + myBatis的单元测试

背景

利用Idea和Maven搭建了一个SSM的web项目,对子模块进行测试是非常重要的,此时我的工程结构如下:
这里写图片描述
Maven中,src下有main和test两个目录,main是用来存放我们的工程文件,而test是用来存放测试文件的,此时我完成了Spring + myBatis的整合,并且要对SeckillMapper接口文件进行单元测试

public interface SeckillMapper {

    int reduceNumber(@Param("seckillId") long seckillId, @Param("killTime") Date killTime);

    Seckill queryById(long seckillId);

    List<Seckill> queryAll(@Param("off") int off, @Param("limit") int limit);
}

单元测试步骤

1. 在pom中添加单元测试的依赖

    <!--3.0的junit是使用编程的方式来进行测试,而junit4是使用注解的方式来运行junit-->
    <dependency>
      <!-- 单元测试 -->
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

2. 创建SeckillMapper测试文件

Idea中有一个快捷键,进入到SeckillMapper文件中,ctrl+shift + t,可以生成该文件的测试文件到test目录下
这里写图片描述

3. 在测试文件中编写测试逻辑

//配置spring和junit整合,这样junit在启动时就会加载spring容器
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring的配置文件
@ContextConfiguration({"classpath:applicationContext-dao.xml"})
public class SeckillMapperTest {

    @Autowired
    private SeckillMapper seckillMapper;

    @Test
    public void queryById() throws Exception {
        long id = 1000;
        Seckill seckill = seckillMapper.queryById(id);
        System.out.println(seckill.getName());

    }

    @Test
    public void queryAll() throws Exception {
        List<Seckill> seckills = seckillMapper.queryAll(0,2);
        for (Seckill seckill : seckills) {
            System.out.println(seckill.getName());
        }
    }

    @Test
    public void reduceNumber() throws Exception {
        int i = seckillMapper.reduceNumber(1000, new Date());
        System.out.println(i);
    }

}

注意在测试文件中添加 RunWith 和 ContextConfiguration注解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值