gpt4 book ai didi

java - Mockito when().thenReturn() 当它应该返回空列表时返回 Null

转载 作者:行者123 更新时间:2023-11-30 05:25:46 30 4
gpt4 key购买 nike

我一直在试图弄清楚为什么当我有 when(controller.findIngredientsByCategory(any()).thenReturn(Collections.emptyList()) 时,我的模拟 findIngredientsByCategory 方法返回 null。这findAll 方法的实现有效。

下面是我的单元测试的实现:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(IngredientController.class)
@ContextConfiguration(classes = {TestContext.class, WebApplicationContext.class})
@WebAppConfiguration
public class IngredientControllerTest {

@Autowired
private WebApplicationContext context;

@Autowired
private MockMvc mvc;

@MockBean
private IngredientController ingredientController;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}

@Autowired
private ObjectMapper mapper;

private static class Behavior {
IngredientController ingredientController;

public static Behavior set(IngredientController ingredientController) {
Behavior behavior = new Behavior();
behavior.ingredientController = ingredientController;
return behavior;
}

public Behavior hasNoIngredients() {
when(ingredientController.getAllIngredients()).thenReturn(Collections.emptyList());
when(ingredientController.getIngredientsByCategory(any())).thenReturn(Collections.emptyList());
when(ingredientController.getIngredientById(anyString())).thenReturn(Optional.empty());
return this;
}
}

@Test
public void getIngredientsByCategoryNoIngredients() throws Exception {
Behavior.set(ingredientController).hasNoIngredients();
MvcResult result = mvc.perform(get("/ingredients/filter=meat"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andReturn();
String content = result.getResponse().getContentAsString();
System.out.println(content);
}

下面是 Controller 的实现:

@RestController
@RequestMapping("/ingredients")
public class IngredientController {

@Autowired
private IngredientRepository repository;

@RequestMapping(value = "/filter", method = RequestMethod.GET)
public List getIngredientsByCategory(@RequestParam("category") String category) {
return repository.findByCategory(category);
}
}

当我告诉它返回一个空列表时,我不确定为什么模拟 Controller 会通过此请求返回 null。如果有人可以帮忙解决这个问题,我将不胜感激!谢谢。

最佳答案

测试中的请求路径是“/ingredients/filter=meat”,但它应该是“/ingredients/filter?category=meat”。因此,似乎没有调用 getIngredientsByCategory

关于java - Mockito when().thenReturn() 当它应该返回空列表时返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58653745/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com