持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第28天,点击查看活动详情
配置测试用例
1.pom.xml文件引入单元测试依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2.mapper新增TestMapper接口类
package com.imooc.reader.mapper;
public interface TestMapper {
public void insert();
}
3.配置TestMapper.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.reader.mapper.TestMapper">
<insert id="insert">
insert into test(content) values('测试内容')
</insert>
</mapper>
代码说明:
namespace="com.imooc.reader.mapper.TestMapper":用来和TestMapper接口类对应起来
4.新增service层
新增TestService
package com.imooc.reader.service;
import com.imooc.reader.mapper.TestMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class TestService {
@Resource
TestMapper testMapper;
public void batchImport(){
for (int i = 0; i < 5; i++) {
testMapper.insert();
}
}
}
代码说明:
@Service:表明该类是Service层
@Resource TestMapper testMapper;:引入testMapper
5.使用idea创建测试用例
6.生成测试用例
package com.imooc.reader.service;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestServiceTest {
@Resource
private TestService testService;
@Test
public void testBatchImport() {
testService.batchImport();
System.out.println("批量导入成功");
}
}
代码说明:
@ContextConfiguration(locations = {"classpath:applicationContext.xml"}):引入配置文件
@RunWith(SpringJUnit4ClassRunner.class):运行时junit4模块
7.执行测试用例
发现控制台报错
解决方案:pom.xml引入对应的依赖,因为这个依赖是tomcat提供的,所以我们要进行配置
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
代码说明:
provided:表示运行时才需要,发布到tomcat不需要
8.重新启动
查看数据是否有值