使用 ServletUriComponentsBuilder 模拟测试返回新添加实体的位置和 201 状态代码的 post 方法

问题描述 投票:0回答:1
@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

spring-boot testing servlets junit mockito
1个回答
0
投票

要解决问题,您可以创建一个模拟

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());
  }
© www.soinside.com 2019 - 2024. All rights reserved.