Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock inherited protected method

I here have a simplified version of my problem. Class A has a protected method. Class B inherits this method.

public class A{
    protected String getString(){
        //some Code
    }
}


public class B extends A{
    public void doSomething(){
        //someCode
        String result = getString();
    }
}

I now write a Unit-Test with Mockito, which is in another package-test and I want to test the doSomething() method. To do that, I need to mock the getString()-call. Since the method is protected and my test-class is in a differnet package, I can't use doReturn(...).when(classUnderTest).getString(). The thing is, that I spy on class B. So I can't use mock(new B(), Mockito.CALLS_REAL_METHODS).

I tried getting the protected method via Reflection:

Method getString = classUnderTest.getClass().getDeclaredMethod("getString");
getString.setAccessible(true);

But I then don't know how to use this inside doReturn().

like image 985
user5417542 Avatar asked Dec 11 '15 14:12

user5417542


2 Answers

You can use 'override and subclass'

B b = new B() {
  @Override
  protected String getString() {
    return "FAKE VALUE FOR TESTING PURPOSES";
  };
};
like image 94
KarlM Avatar answered Nov 13 '22 07:11

KarlM


There might be a cleaner way of doing this, but here goes...

  1. Create a mock for "A"
  2. Create another class that extends B and overrides the method
  3. Make the overridden method call the mock

For example...

private A partialMock;
private B classUnderTest;

@Before
public void setup() {
    partialMock = mock(A.class);
    classUnderTest = new B() {
        @Override
        protected String getString() {
            return partialMock.getString();
        }
    };
}

@Test
public void shouldDoSomething() {

    when(partialMock.toString()).thenReturn("[THE MOCKED RESPONSE]");

    classUnderTest.doSomething();

    // ...verify stuff...
}

Obviously you don't even need to use mocking, you can just return something directly from the overridden method.

like image 31
BretC Avatar answered Nov 13 '22 07:11

BretC