Codearte/catch-exception

Mockito spies call real methods instead of stubs with catchException

igorini opened this issue · 2 comments

Hi Everyone,

catch-exception is cool, but I think I encountered a potential issue. Sorry if this is the expected behaviour or if this was reported already. If you're aware of a workaround, please let me know. :)

I'm using version 1.4.4, Mockito and Hamcrest. I found out that real methods of a spy are called instead of stubs when using catchException when I explicitly stub the method. Consider the example below.

The class I'm trying to test:

public class SomeClass {

    public Object method(String text) throws Exception {
        Object object = otherMethod(text);

        if (object == null) {
            throw new Exception();
        }

        return object;
    }

    public Object otherMethod(String text) {
        return "some other text";
    }
}

The test below fails as the real otherMethod gets called during the test.

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {

    @Spy
    private SomeClass someClass = new SomeClass();

    @Test
    public void testMethod() throws Exception {
        // Stubbing otherMethod to return null
        doReturn(null).when(someClass).otherMethod(any());

        catchException(someClass).method("some text");

        assertThat(caughtException(), instanceOf(Exception.class));
    }
}

Could you test your code with 2.x?

closing, because 2.0 line do not rely on mockito