- 修改要測試的子項目的pom文件,添加Spring-boot-測試包的依賴。
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
所有的java要進行test,都必須要導入Junit,只是此處省略了代碼而已。
- 在測試目錄下,創建一個測試類。使用
@SpringBootTest進行注解
。
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
Logger logger = LoggerFactory.getLogger(DemoControllerTest.class);
@Before
public void setup(){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void greetingTest() throws Exception {
logger.info("start...");
mockMvc.perform(MockMvcRequestBuilders.get("/rest/hello").contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void getUserTest() throws Exception {
logger.info("start...");
mockMvc.perform(MockMvcRequestBuilders.get("/rest/user").contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
說明: 上述代碼測試的是Spring Boot的REST能力。是一個典型的測試程序。以后都可以按照這么搞。