I have a class that has a private class variable initialized like
public class MyClass{
private BusinessObject businessObject = BusinessObjectGenerator.getBusinessObject();
public MyClass(){
}
public Object myMethodToTest(){
return businessObject.getObject();
}
}
Now, I’m trying to unit test myMethodToTest I want to send in a mock object in place of businessObject. I use mockito for mocking and use spy(new MyClass()) for partial mocking but having trouble with mocking the call to get businessObject.
1. Is it possible to mock the call to the businessObject? If so how?
2. How can I refactor this code to help while writing unit test. Any resources pointing towards this would be of great help.
Thanks!
To properly refactor this code you’d:
Now you can inject your mock into the class yourself at the test site.
I’d recommend doing this using dependency injection with a framework like Guice. It will be worth your time.