Mocking a call on a public method of an abstract class without subclassing the abstract Class, using mockito prefererably

java, junit, mocking, mockito, unit-testing

Solution

Assumption: if you write unit test, I guess you still can modify tested method a bit.

Solution:

- extract static method call to overridable method:

public someObject methodUnderTest() {
    SomeObject obj = getSomeObject();

    if(obj!=null){
      obj.someOtherMethod();
    }

    return someThing;
}

protected SomeObject getSomeObject() {
    return SomeAbstractClass.someMethod();
}

- then you can use Mockito Spy to partially mock the object you actually test:

private ClassUnderTest classUnderTest;

@Before
public void setUp() {
    classUnderTest= new ClassUnderTest();
    classUnderTest = Mockito.spy(classUnderTest);
}

@Test
public void test() {
    SomeObject someObject = Mockito.mock(SomeObject.class);
    when(classUnderTest.getSomeObject()).thenReturn(someObject);
    classUnderTest.methodUnderTest();
    verify(someObject).someOtherMethod();
}

@Test
public void testNull() {
    when(classUnderTest.getSomeObject()).thenReturn(null);
    classUnderTest.methodUnderTest();
    verify(something);
}

Problem

I am writing an unit testing using JUNIT + Mockito to test a method like : ``` public someObject methodUnderTest(){ SomeObject obj = SomeAbstractClass.someMethod(); if(obj!=null){ obj.someOtherMethod(); } return someThing; } ``` And I would like to mock the call on `abstract Class "SomeAbstractClass"` mentioned in above code fragment so i can verify call on "obj" like : ``` verify(SomeAbstractClass).someMethod(); verify(obj).someOtherMethod(); ``` I have tried using mockito features like : Mockito.CALLS_REAL_METHODS Mockito.RETURNS_MOCKS but they don't work due to dependencies not available to the SomeAbstractClass. Note: 1) SomeObject is an Interface. 2) I need a technique to test above code fragment. I am constrained to use the above code fragment and cannot change the code fragment.

Original source