一、测试接口

可以通过单元测试来测试我们的接口是否正常工作, 单元测试放置于 src\test
ReqTests.java

  1. import com.example.hello.controller.HelloController;
  2. import org.junit.Before;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. import org.springframework.test.web.servlet.MockMvc;
  9. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  10. import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
  11. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  12. import org.springframework.test.web.servlet.setup.MockMvcBuilders;
  13. @RunWith(SpringRunner.class)
  14. @SpringBootTest
  15. public class HelloTests {
  16. @Test
  17. public void contextLoads() {
  18. }
  19. private MockMvc mvc;
  20. @Before
  21. public void setUp() throws Exception {
  22. mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
  23. }
  24. @Test
  25. public void getHello() throws Exception {
  26. mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
  27. .andExpect(MockMvcResultMatchers.status().isOk())
  28. .andDo(MockMvcResultHandlers.print())
  29. .andReturn();
  30. }
  31. }

如果通过测试, 控制台将打印出信息:

  1. MockHttpServletRequest:
  2. HTTP Method = GET
  3. Request URI = /
  4. Parameters = {}
  5. Headers = [Accept:"application/json"]
  6. Body = <no character encoding set>
  7. Session Attrs = {}
  8. Handler:
  9. Type = com.example.demo.controller.HelloController
  10. Method = public java.lang.String com.example.demo.controller.HelloController.index()
  11. Async:
  12. Async started = false
  13. Async result = null
  14. Resolved Exception:
  15. Type = null
  16. ModelAndView:
  17. View name = null
  18. View = null
  19. Model = null
  20. FlashMap:
  21. Attributes = null
  22. MockHttpServletResponse:
  23. Status = 200
  24. Error message = null
  25. Headers = [Content-Type:"application/json;charset=utf-8", Content-Length:"19"]
  26. Content type = application/json;charset=utf-8
  27. Body = Hello Spring Boot !
  28. Forwarded URL = null
  29. Redirected URL = null
  30. Cookies = []

可以看到 MockHttpServletResponse.Body 中打印出正确的响应结果

二、测试类

比如我们要测试一个继承了 JpaRepository 的 UserRepository 是否正常:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTests {
    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {
        // 查询
        User user = userRepository.findById(1l).get();
        System.out.println(user);
    }
}