编写单元测试,测试你的代码
编写单元测试三步骤: 1.准备数据:db、mock第三方服务、MQ、redis、dubbo 2.调用测试方法 3.验证期望结果
依赖junit包
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.38</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.11.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
直接调用方法单测
public class MyServiceTest extends BaseTest {
@Autowired
private MyService myService;
@Test
public void queryByIdTest() {
loadTestData("MyServiceTest.queryByIdTest")
Long id = -1000L;
User user = myService.queryById(id);
Assert.assertEquals(23, user.getAge());
}
}
期望异常
public class MyServiceTest extends BaseTest {
@Autowired
private MyService myService;
@Test(expected = BusinessRunTimeException.class)
public void queryByAgeTest() {
loadTestData("MyServiceTest.queryByAge")
int age = -23;
List<User> userList = myService.queryByAge(age);
}
}
mock掉第三方系统
@service
public class MyService {
@Reference
private RightService rightService;
public List<String> queryUserRight(Long id) {
return rightService.getRights(id);
}
}
public class MyServiceTest extends BaseTest {
@Autowired
private MyService myService;
@mocked
private RightService rightService
@Test
public void queryUserRightTest() {
loadTestData("MyServiceTest.queryUserRightTest")
mockUserRights();
Long id = -1000L;
List<String> rights = myService.queryUserRight(id);
Assert.assertTrue(rights.contains("view"));
}
private void mockUserRights() {
new Expectations() {{
rightService.getRights(-1000L)
result = Arrays.asList("view","update");
}}
}
}
|