Yurii Kozachok
Yurii Kozachok

Reputation: 645

Test abstract class which extends another class

I have an abstract class B which extend another abstract class A. In abstract class A I have protected method convert. I want to test method foo which invoke method convert from base class which doesn't have implementation. How I can mock method convert if I can't change convert method signature.

abstract class B extends A {
    public void foo(Object someObject) {
        Object convertedObject = convert(someObject);
        //logic for testing
    }
}

abstract class A {
    protected abstract Object convert(Object some object);      
}

I use Mockito.spy() for invoking real methods but convert method is not available for mocking (throught Mockito.when (...).thenReturn (...) because it is protected.

B b = Mockito.spy(B.class);

Give me idea how I can test method foo.

Upvotes: 1

Views: 2109

Answers (1)

Sergii Bishyr
Sergii Bishyr

Reputation: 8641

Mockito can't mock abstract classes. But you can have a subclass for your test purpose which implement your class B and then spy on it.

@RunWith(MockitoJUnitRunner.class)
public class BTest {

    @InjectMocks
    @Spy
    private FakeB b;

    @Test
    public void testSomething() {
        when(b.convert(any())).thenReturn(something);
    }

    public static class FakeB extends B {
        protected Object convert(Object someobject) {
            return null;
        }  
    }
}

With this approach you can easily mock your abstract methods and test non-abstract ones in your abstract classes. Of course the downside is that you have to crate a fake test classes that subtypes your abstract classes. But I think it shouldn't be a big issue.

Upvotes: 1

Related Questions