AsMartynas
AsMartynas

Reputation: 167

Mokito cannot mock method and assert is always failed

I cannot mock my getUserCards to return empty list. It always take info from the database. Do you have any ideas? I attach my get request and mockito implementation. I want to set up getUserCards method to always return an empty list, but I cannot be mocked

@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);
}

Get

@RequestMapping(value = "/cards", method = RequestMethod.GET)
@JsonView(Views.Public.class)
public List<Card> getUserCards(

{
  session.getEntityUserId());
}

Upvotes: 1

Views: 68

Answers (1)

homik
homik

Reputation: 563

You have to inject your mock into the controller otherwise your controller will use spring bean from configuration.

You can pass the mock to Controller constructor or read about @InjectMocks/@MockBean annotation.

Upvotes: 2

Related Questions