spring boot 完成单元测试
下面是基于spring boot框架进行单元测试的代码片段
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class) // 指定spring-boot的启动类
public class MessageTest {
@Test
public void sendMessageTest(){
MQCPMessage mqcpMessage = new MQCPMessage();
mqcpMessage.sendMessage();
}
}
需要使用到的pom依赖:
<!--
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
spring-boot-starter-test 包就够了,其中间接依赖了 spring-test 这个包。
关键几个注解:
@RunWith(SpringJUnit4ClassRunner.class)
主要是spring和junit4的集成。可以使用 @Test注解对测试方法进行标识。
@SpringBootTest(classes = Application.class) // 指定spring-boot的启动类
@SpringBootTest是spring boot 的测试注解,里面可以指定src 源码中的启动类,一般是Application.java
所以在运行UT的时候,服务是需要启动的,从使用service注解就可以看出了。