How do I subclass a parent class with a private constructor so that I can mock it?
I have refactored my code such that when it makes a call to a third party library, the calls are wrapped so that I can mock the class and create a fake wrapper. I can then in theory return whatever I want to test my production code using dependency injection etc.
For a few of the library calls, a single object instance is returned which in itself is a specific library object type. In the production code, this then has subsequent calls made upon that object.
This is illustrated in the code below:
public class MyWrapper
{
public LibraryObject getX()
{
LibraryObject x = ExternalLibrary.getX();
return x;
}
}
public class MyProductionCode
{
public void DoX()
{
LibraryObject lo = MyWrapper.getX();
ProductionType pt = lo.doSomething();
}
}
How do I fake the method doSomething() ? My first thought was instead of returning an instance object from the wrapped call, return an object which is of the same type. So MyWrapper code could be enhanced as follows:
public class MyWrapper
{
public LibraryObject MyWrappedCall()
{
//LibraryObject x = ExternalLibrary.getLibObject();
MyMockLibraryObject mlo;
return mlo;
}
public class MyMockLibraryObject extends LibraryObject
{
public ProductionType doSomething()
{
ProductionType pt;
return pt;
}
}
}
The problem with this is that the parent class has a private constructor, so it cannot be subclassed.
Does anybody have any suggestions of how to get around this?
Aucun commentaire:
Enregistrer un commentaire