【问题标题】:Mock a service to return an empty list to test 404 status code模拟一个服务返回一个空列表来测试 404 状态码
【发布时间】:2020-09-16 17:58:46
【问题描述】:

我正在尝试测试此 REST 服务,以便在 itemService.getActiveItems() 返回空的 List 时引发 NOT_FOUND (404) 错误:

@GetMapping("/items/active")
public ResponseEntity<List<ItemEntity>> getActiveItems() {

    List<ItemEntity> activeItems = itemService.getActiveItems();
    if (activeItems.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else {
        return new ResponseEntity<>(activeItems, HttpStatus.OK);
    }
}

我使用 TestRestTemplate 进行测试:

     @Mock
     private ItemService itemService;
    
            @Test
            public void activeItemsTest() {
            private TestRestTemplate templateAuth;
        
        when(itemService.getActiveItems()).thenReturn(new ArrayList());
            
                    ResponseEntity<List<ItemEntity>> result = templateAuth.exchange("/items/active", HttpMethod.GET,
                            null, new ParameterizedTypeReference<List<ItemEntity>>() {
                            });
                    Assertions.assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
        }

我试图让"/items/active" 端点返回new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND);,因为我已经模拟itemService.getActiveItems() 以返回一个空的ArrayList。当我测试 result.getStatusCode() 时不包含 404。我应该如何修改我的测试以返回 404 错误代码?

【问题讨论】:

  • 那么当你测试这个时,activeItems 包含什么?
  • 你需要修复你的activeItemsTest(){} 你里面有private TestRestTemplate templateAuth;
  • 如果你可以使用junit5,你可能想看看这个例子。您可以@autowire 实际的服务类,resttempalte..etc:gist.github.com/Jet-C/6c4d3ebf91f8d6d6ccba0468c2dbef95

标签: java spring rest junit mocking


【解决方案1】:

您可以使用 JUnit 5 并使用 @ExtendWith(MockitoExtension.class) 注释类 和@SpringBootTest。然后改变

 @Mock
 private ItemService itemService;

 @SpyBean
 private ItemService itemService;

这样您就可以模拟自动装配到控制器中的服务的行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多