項目結構如下
1 引入測試的 maven 依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.1.0.RELEASE</version> <scope>test</scope> </dependency>
2 編寫測試類
//導包 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; //測試類 @RunWith(SpringRunner.class) @SpringBootTest public class ClientuseApplicationTests { @Test public void contextLoads() { } }
說明:1)在測試類中可以注入需要的 Service 類,可以使用 springboot 的聲明式注入。
如果測試接口可以使用 MockMvc 進行模擬
/** * 模擬mvc測試對象 */ private MockMvc mockMvc;
具體詳情可以搜索 MockMvc 使用方法。
2) 在測試類中需要引入額外的依賴時可以使用 <scope> 來選擇適用范圍。例如
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>