说明

测试代码「src/test」中文件不会打入 jar包

1
mvn clean package -Dmaven.test.skip=true

注意

项目中同一个srctest 测试类中可以访问 main中资源文件

classpath:spring.xml

IDEA 安装 JUnit 插件

  • 安装 JUnitGenerator V2.0,已有的 JUnit 保留

  • 配置

    UTOOLS1576595373491.png

SSM

maven

依赖引入spring-test、 JUnit

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

IDEA JUnit 插件配置模板

1
2
3
4
5
6
7
8
9
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring.xml"})

技巧

  • 根据 Controller 生成 ControllerTest 类,测试 Service 接口功能
  • 根据 ServiceImpl 类生成 ServiceImplTest 类,测试 Dao 接口功能

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//整合junit和spring,让junit在启动时候加载springIOC容器
@RunWith(SpringJUnit4ClassRunner.class)
//spring的配置文件
//如果测试类位于src/test/java下,而 spring.xml处于src/main/java下,所以需要使用file来获取
//@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring.xml"})
@ContextConfiguration({ "classpath:spring.xml" })
public class SeckillServiceTest {
@Autowired
private SeckillService seckillService;

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Test
public void testGetSeckillList() {
List<Seckill> seckills = seckillService.getSeckillList();
logger.info("list={}", seckills);
}
}

Spring boot

maven

包括 JUnit、Hamcrest、Mockito

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

IDEA JUnit 插件配置模板

UTOOLS1576595320398.png

1
2
3
4
5
6
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest

生成基础测试代码

UTOOLS1576595586761.png

断言测试

1
2
3
4
5
6
7
8
9
@Autowired
private UserMapper userMapper;

@Test
public void select() {
List<User> users = userMapper.selectList(null);
Assert.assertEquals(users.size(), 17);
Assert.assertTrue(0==0);
}

@Before、@Test、@After 使用

@Before

准备环境

@Test

测试代码

@After

清理环境