How to inject method (using reflection) into super class without extending tested class?
I need to replace getExternalData() to test the logic inside someMethod(). I cannot change tested classes – because of that I was thinking about injecting method.
I have flowing classes:
public class B extends A{
public String someMethod(){
String someString = super.getExternalData();
//logic to be tested - manipulating on someString
return someString;
}
}
public class A{
public String getExternalData(){
//some Logic that generates "externalData" string
return externalData;
}
}
And test:
public class CesTest{
@Test
public void someMethodTest()(
B instance = new B();
//...
//...
assertEquals("expectedData", instance.someMethod());
}
}
Simple answer is you can’t without doing some really odd stuff that would result in your not testing the class under test but some odd mocked-out version of the class under test. You need to do whatever setup is required to have
getExternalDatareturn the appropriate value. That being said,class Ashould be written in such a was that amockcould be injected to provide thisexternal datawithout hitting an external resource.