JUnit 单元测试
一.JUnit 介绍
JUnit 是 Java 中最有名的单元测试框架,用于编写和运行可反复的测试,少数 Java 的开发环境都曾经集成了 JUnit 作为单元测试的工具。好的单元测试能极大的进步开发效率和 H5 游戏。
测试类命名规定:被测试类 +Test,如 UserServiceTest
测试用例命名规定:test+ 用例办法,如 testGet
Maven 导入 junit、sprint-test
<dependencies>
<!-- Test Unit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.10.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- Json 断言测试 -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 单元测试插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>2.20</version>
</dependency>
</dependencies>
<configuration>
<!-- 是否跳过测试 -->
<skipTests>false</skipTests>
<!-- 排除测试类 -->
<excludes>
<exclude>**/Base*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
二.Service 层测试示例
创立 Service 层测试基类,新建 BaseServiceTest.java
// 配置 Spring 中的测试环境
@RunWith(SpringJUnit4ClassRunner.class)
// 指定 Spring 的配置文件门路
@ContextConfiguration(locations = {“classpath*:/spring/applicationContext.xml”})
// 测试类开启事务, 须要指定事务管理器, 默认测试实现后, 数据库操作主动回滚
@Transactional(transactionManager = “transactionManager”)
// 指定数据库操作不回滚, 可选
@Rollback(value = false)
public class BaseServiceTest {
}
测试 UserService 类,新建测试类 UserServiceTest.java
public class UserServiceTest extends BaseServiceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class);
@Resource
private UserService userService;
@Test
public void testGet() {UserDO userDO = userService.get(1);
Assert.assertNotNull(userDO);
LOGGER.info(userDO.getUsername());
// 减少验证断言
Assert.assertEquals("testGet faield", "Google", userDO.getUsername());
}
}