- 修改要測(cè)試的子項(xiàng)目的pom文件,添加Spring-boot-測(cè)試包的依賴。
<!-- 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要進(jìn)行test咽块,都必須要導(dǎo)入Junit,只是此處省略了代碼而已欺税。
- 在測(cè)試目錄下侈沪,創(chuàng)建一個(gè)測(cè)試類。使用
@SpringBootTest進(jìn)行注解
晚凿。
@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());
}
}
說(shuō)明: 上述代碼測(cè)試的是Spring Boot的REST能力亭罪。是一個(gè)典型的測(cè)試程序。以后都可以按照這么搞歼秽。