jeudi 23 avril 2020

UnfinishedStubbingException when passing mocked class as an argument in thenThrow

Can I pass mocked object as an argument to thenThrow() method? I have something like this:

public class MyException extends Exception {
    public MyException(MockedClass mockedClass) {
        super("My message:" + mockedClass.doSth("foo"));
    }
}

public class TestedServiceTest {
    @Mock
    MockedClass mockedClass;

    @Mock
    AnotherClass anotherClass;

    @Before
    public void init() {
        when(mockedClass.doSth(anyString())).thenAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return invocation.getArgument(0);
            }

        });
    }

    @Test
    public void notWorkingTestMethod() {
        when(anotherClass.doSomething()).thenThrow(new MyException(mockedClass));
    }

notWorkingTestMethod() throws org.mockito.exceptions.misusing.UnfinishedStubbingException However if I use the same technique on void method it doesn't complain anymore:

    @Test
    public void workingTestMethod() {
        doThrow(new MyException(mockedClass)).when(anotherClass).doSomethingVoid();
    }
}

Is there any other possible reason it doesn't work?

Aucun commentaire:

Enregistrer un commentaire