我一直在试图弄清楚为什么我的模拟findIngredientsByCategory方法返回null,即使我有when(controller.findIngredientsByCategory(any()).thenReturn(Collections.emptyList())
。这个实现对于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);
}
以下是控制器的实现:
@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);
}
}
我不确定为什么模拟控制器在这个请求中返回null,当我告诉它返回一个空列表时。如果有人能帮忙解决这个问题,我将非常感激!谢谢。