使用Spring Boot和JUnit进行单元测试Rest服务

时间:2018-05-30 12:47:16

标签: rest unit-testing spring-boot junit4 junit5

我有一个基本的SpringBoot应用程序。使用Spring Initializer,JPA,嵌入式Tomcat,Thymeleaf模板引擎和包作为可执行的JAR文件。我已经定义了这个Rest方法来获取用户

  @GetMapping(path = "/api/users/{id}", 
                consumes = "application/json", 
                produces = "application/json")
    public ResponseEntity<User> getUser
                                    (HttpServletRequest request, 
                                    @PathVariable long id) {

        User user = checkAccess(request, id);
        return ResponseEntity.ok(user);

    }

我已经创建了这个Junit来测试它

@ContextConfiguration(classes={TestSystemConfig.class})
@RunWith(SpringRunner.class)
@WebMvcTest(UserResourceController.class)
public class UserResourceControllerTests {

    @Autowired
    private MockMvc mvc;


    @MockBean
    private UserResourceController UserResourceController;

    @Test
    public void getUser() throws Exception {

        mvc.perform(get("/api/users/1")
                   .with(user("pere.peris@gmail.com").password("password"))
                   .contentType(APPLICATION_JSON))
                   .andExpect(status().isOk());

    }
}

但是当我运行测试时出现了这个错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Name for argument type [long] not available, and parameter name information not found in class file either.
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)

1 个答案:

答案 0 :(得分:2)

原因是你在嘲笑你的控制器。如果您有@WebMvcTest(UserResourceController.class)

,则无需这样做

这应该有效。

@ContextConfiguration(classes={TestSystemConfig.class})
@RunWith(SpringRunner.class)
@WebMvcTest(UserResourceController.class)
public class UserResourceControllerTests {

    @Autowired
    private MockMvc mvc;

    @Test
    public void getUser() throws Exception {

        mvc.perform(get("/api/users/1")
                   .with(user("pere.peris@gmail.com").password("password"))
                   .contentType(APPLICATION_JSON))
                   .andExpect(status().isOk());

    }
}