There is a way to achieve what you want - it is called "partial mocking". See this question for more details - Use Mockito to mock some methods but not others.
Given a ClassUnderTest
as follows:
class ClassUnderTest {
public void init() {
throw new RuntimeException();
}
public void deleteX() {
// some things
init();
}
}
This test will pass:
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ClassUnderTestTest {
@Spy
private ClassUnderTest classUnderTest;
@Test
public void test() throws Exception {
// given
doNothing().when(classUnderTest).init();
// when
classUnderTest.deleteX();
// then
verify(classUnderTest).init();
}
}
All method invocations on object annotated with @Spy
will be real, except for mocked ones. In this case init()
invocation is mocked to do nothing, instead of throwing an exception.
If you need dependencies injected into class under test, that needs to be done in @Before
method, e.g.:
private ClassUnderTest classUnderTest;
@Before
public void setUp() {
ClassUnderTest cut = new ClassUnderTest();
// inject dependencies into `cut`
classUnderTest = Mockito.spy(cut);
}