引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<optional>true</optional>
</dependency>
创建单元测试类
创建Junit测试类,并用到 @RunWith,@SpringBootTest两个注解。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {StartupRunner.class})
public class UserEntityTestTest {
@Autowired
private JunitService mockService;
@Test
public void test1() throws Exception {
junitService.printJunitServiceName();
}
}
@SpringBootApplication
public class StartupRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("hello CommandLineRunner");
}
public static void main(String[] args) {
SpringApplication.run(StartupRunner.class, args);
}
}
@SpringBootTest 标注一个测试类,如果该注解没有指定加载的启动配置类,那么会自动搜索标注有@SpringBootApplication注解的类。如果需要手工指定,那么通过注解的classes属性即可。找到启动类后注入服务,随后可以进行测试。
创建Mock
通过@MockBean注解字段,通过BDDMockito的方法生成模拟接口的返回值或抛出的异常,然后进行测试。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {StartupRunner.class})
public class UserEntityTestTest {
@MockBean
private JunitService mockService;
@Test
public void test1() throws Exception {
BDDMockito.given(mockService.printMsg()).willReturn("hello");
String msgRet = mockService.printMsg();
Assert.assertTrue(msgRet.equals("hello"));
}
}
参考
41.3 Testing Spring Boot applications
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/