1

I use Mockito 1.9.5.while trying to mock a method that located in the service I'm testing. I know that it's not usual to mock methods of service that you are testing but that method is just a part of complex logic for fetching configuration from DB.

What I want to achieve is just

when ( mockService.isFatureActive () ).thenReturn ( false );

@RunWith ( MockitoJUnitRunner.class )
public class MockSpyTestService {

    @Spy
    @InjectMocks
    private MockSpyTestService mockService = new MockSpyTestService ();

    @Before
    public void init () {
        mockService.setObjectFactory ( new ObjectFactory () );
    }

    @Test
    public void verifyMockService () {
        when ( mockService.isFatureActive() ).thenReturn ( false ); //real  isFatureActive() called
        verify ( mockService, times ( 1 ) ).isFatureActive();
    }
}

According to documentation that should work just fine. Instead I'm getting invocation of real method - isFatureActive()

fish
  • 11
  • 3
  • Unfortunatelly that answer didn't help. In my case isFatureActive() is public in public class MockSpyTestService – fish Mar 29 '16 at 15:25
  • That answer should have everything you need. The real method is called because of `when (mockService.isFatureActive())`. If you use `doReturn(false).when(mockService).isFatureActive();` you should be OK. – Magnilex Mar 29 '16 at 15:40
  • (1) remove the instantiation of the service `= new MockSpyTestService ();`, (2) replace `thenReturn` at the end of the methods chain with `doReturn` at the beginning of the method chain, (3) close the parenthesis immediately after your service variable, before you call the method in this way: `(mockService).isFatureActive()` – Marco Lackovic Sep 25 '20 at 08:55

0 Answers0