首页 > 学院 > 开发设计 > 正文

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

2019-11-08 02:30:20
字体:
来源:转载
供稿:网友

背景

利用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注解


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表