@PostMapping(path= "/users/{username}/events")
public ResponseEntity<Object> createEventsForUser(@PathVariable String username, @RequestBody @Valid EventBean event){
event.setUsername(username);
EventBean savedEvent = eventJPAService.save(event);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{eventId}")
.buildAndExpand(savedEvent.getEventId())
.toUri();
return ResponseEntity.created(location).build();
}
这是我想使用 Junit 和 mockito 测试的 post 方法的代码。我该怎么做?
我试过这个:
@Test
public void testCreateEventsForUser() {
String username = "testuser";
EventBean newEvent = new EventBean(404, "testuser","New Event", "Planning", LocalDate.now());
int expectedEventId = 404;
// Mock the behavior of eventJPAService.save
when(eventJPAService.save(newEvent)).thenReturn(new EventBean(expectedEventId,"testuser" ,"New Event", "Planning", LocalDate.now());
ResponseEntity<Object> response = eventController.createEventsForUser(username, newEvent);
// Verify the response status and location
assertEquals(201, response.getStatusCodeValue());
URI location = response.getHeaders().getLocation();
assertEquals("/users/testuser/events/404", location.getPath());
}
出现错误: 当前没有 ServletRequestAttributes
要解决问题,您可以创建一个模拟
HttpServletRequest
并使用 RequestContextHolder
将其设置为当前请求属性,因此测试用例将如下所示(我还更新了已弃用的用于检查 statusCode 的内容):
@Test
public void testCreateEventsForUser() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/users/testuser/events");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
String username = "testuser";
EventBean newEvent = new EventBean(404, "testuser","New Event", "Planning", LocalDate.now());
int expectedEventId = 404;
// Mock the behavior of eventJPAService.save
when(eventJPAService.save(newEvent)).thenReturn(new EventBean(expectedEventId,"testuser" ,"New Event", "Planning", LocalDate.now());
ResponseEntity<Object> response = eventController.createEventsForUser(username, newEvent);
// Verify the response status and location
assertEquals(201, response.getStatusCode().value());
URI location = response.getHeaders().getLocation();
assertNotNull(location);
assertEquals("/users/testuser/events/404", location.getPath());
}