我无法模拟我的getUserCards返回空列表。它总是从数据库获取信息。你有什么想法?我附上我的get请求和模仿实现。我想将getUserCards方法设置为始终返回一个空列表,但不能被嘲笑
@Before
public void setUp() throws Exception{
//cards.add(new Card());
CardService mock = Mockito.mock(CardService.class);
Mockito.when(mock.getUserCards("1234"))
.thenReturn(cards);
}
@Test
public void testMockCards() throws Exception{
mockMvc = MockMvcBuilders.standaloneSetup(cardController).build();
MockHttpServletResponse response = mockMvc.perform(
MockMvcRequestBuilders.get("/cards")
)
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse();
ObjectMapper mapper = new ObjectMapper();
List<Card> cardResponse = mapper.readValue(response.getContentAsString(),
new TypeReference<List<Card>>(){});
Assert.assertEquals(cards, cardResponse);
}
获取
@RequestMapping(value = "/cards", method = RequestMethod.GET)
@JsonView(Views.Public.class)
public List<Card> getUserCards(
{
session.getEntityUserId());
}
答案 0 :(得分:2)
您必须将模拟注入到控制器中,否则您的控制器将使用配置中的spring bean。
您可以将模拟传递给Controller构造函数,或阅读有关@ InjectMocks / @ MockBean注释的信息。