使用Spring Boot和JUnit对Rest服务进行单元测试
我有一个基本的SpringBoot应用程序。使用Spring初始值设定项、JPA、嵌入式Tomcat、Thymeleaf模板引擎,并将包作为可执行JAR文件。我已经定义了这个Rest方法来获取一个用户使用Spring Boot和JUnit对Rest服务进行单元测试,rest,unit-testing,spring-boot,junit4,junit5,Rest,Unit Testing,Spring Boot,Junit4,Junit5,我有一个基本的SpringBoot应用程序。使用Spring初始值设定项、JPA、嵌入式Tomcat、Thymeleaf模板引擎,并将包作为可执行JAR文件。我已经定义了这个Rest方法来获取一个用户 @GetMapping(path = "/api/users/{id}", consumes = "application/json", produces = "application/json") public Re
@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);
}
但是我在运行测试时遇到了这个错误:
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)
原因是你在嘲笑你的控制器。当您有
@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());
}
}
原因是你在嘲笑你的控制器。当您有
@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());
}
}
你为什么嘲笑你的userResourceController。去掉那个。不是needed@pvpkiran,请转换为答案。你试过了吗。它能用吗?是的,谢谢,现在能用了。你为什么要嘲笑你的userResourceController。去掉那个。不是needed@pvpkiran,请转换为答案。你试过了吗。它能用吗?是的,谢谢,现在能用了