1

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.

Daniel Bleisteiner
  • 3,060
  • 1
  • 28
  • 44
Yurii Kozachok
  • 493
  • 1
  • 5
  • 16
  • 1
    test it through a non-abstract sub-class. you'll need an instance of B to test it, but you can't instantiate B since it's abstract – Stultuske Dec 20 '17 at 14:12
  • Possible duplicate of [How to unit test abstract classes: extend with stubs?](https://stackoverflow.com/questions/243274/how-to-unit-test-abstract-classes-extend-with-stubs) – LenglBoy Dec 20 '17 at 14:13
  • You Should use PowerMockito – pvpkiran Dec 20 '17 at 14:13

1 Answers1

1

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.

Sergii Bishyr
  • 7,377
  • 5
  • 29
  • 53