jUnit skip Method-Call in injectmock-method in a test

15,854

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);
}
Share:
15,854
LenglBoy
Author by

LenglBoy

Updated on June 04, 2022

Comments

  • LenglBoy
    LenglBoy almost 2 years

    I've got a @InjectMocks cut which is the Class i want to test. There is a deleteX() and a init() Method in it. deleteX() is calling init() before finishing - how can i skip this call in my test, because every time i just get a NullPointer Exception.

    public void deleteX() {
        // some things
        init();
    }
    

    I just want to skip it, because I've got test methods for both of them and don't want big and double code. I can't do Mockito.doNothing().when(cut).deleteX(); because @InjectMocks is not a Mockobject.