一.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());
}
}