3. Spring Boot 的代码测试

  1. 修改要测试的子项目的pom文件,添加Spring-boot-测试包的依赖。


    org.springframework.boot
    spring-boot-starter-test
    test

所有的java要进行test,都必须要导入Junit,只是此处省略了代码而已。

  1. 在测试目录下,创建一个测试类。使用@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能力。是一个典型的测试程序。以后都可以按照这么搞。

你可能感兴趣的:(3. Spring Boot 的代码测试)