markusf/spring-test-portlet-mvc

Mocks are ignored

Closed this issue · 2 comments

Mocks initiated by Mockito are completely ignored.

My controller use a service which is autowired. Fow now the test throws a null pointer exception.

@Mock
private MyCustomService myCustomService;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testRenderMyController() throws Exception {
    
    when(myCustomService.doSomething(anyString())).thenReturn(something());
    
    MyController controller = new MyController();
    
    standaloneSetup(controller)
        .build()
        .perform(render())
        .andExpect(view().name("step1"))
        .andReturn();
}

@markusf Is there currently a way to make this work?

Hey @AlexLevesque, I think you are using Mockito in a wrong way, cause you actually never inject your mocked custom service into the controller.

As far as I remember you have to move the controller a member and annotate it with @Injectmocks. In this case Mockito will instantiate your controller and inject the mocks it found (checking on @mock). Another way would be just creating a setter method on MyController and injecting it manually:controller.setMyCustomService(myMockedCustomService)

You are right! I did @Injectmocks, find it more clean. thank you!