Jay
Jay

Reputation: 4465

Issue mocking a class variable value in java

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!

Upvotes: 0

Views: 1646

Answers (1)

cfeduke
cfeduke

Reputation: 23226

To properly refactor this code you'd:

private BusinessObject businessObject;

public void setBusinessObject(BusinessObject instance) {
    businessObject = instance;
}

private BusinessObject getBusinessObject() {
    if (businessObject == null) {
        // represents existing implementation in original code sample
        businessObject = BusinessObjectGenerator.getBusinessObject();
    }
    return businessObject;
}

/* rest of your code */

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.

Upvotes: 4

Related Questions