Nakul Upadhya
Nakul Upadhya

Reputation: 488

Mocking method calls in a different class apart from test class without PowerMock

I am having some trouble writing a unit test for my application. Currently, I am testing class A. In the method of class A I am testing, it makes a call to a helper class's method, which then calls another method inside the same helper class(getKeyObject) whose only function is to call a static method of a class contained in a framework I am using(buildKeyObject()). I am trying to stub getKeyObject() so that it returns a mock of the Object that is normally generated, but I have no idea on how to proceed.

One way I thought was to utilize PowerMockito and use PowerMockito.mockStatic(ClassInFramework.class) method to create a mock of the class in the framework I am using, and then use when(ClassInFramework.buildKeyObject()).thenReturn(KeyObjectMock), but due to some limitations on the work I am doing, I am forbidden to use PowerMockito. I am also unable to use Mockito.spy or the @spy annotation because of the same reasons.

class ATest{

    public A aInstance = new A(); 

    @Test
    public void test(){
        KeyObject keyObjectMock = Mockito.mock(KeyObject.class); 
        /*
        between these 2 lines is more mockito stuff related to the KeyObjectMock above. 
        */
        String content = aInstance.method1(); 
        Assert.assertEquals(content, "string")
    }
}
class A{
    public RandomClass d = new RandomClass()
    public String method1(){
        Helper helper = new Helper(); 
        Object a = helper.method2()
        return d.process(a); 
    }
}
class Helper{
    public Object method2(){
        KeyObject keyObject = getKeyObject(); 
        Object object = keyObject.getObject(); 
        return object; 
    }
    public KeyObject getKeyObject(){
        return ClassInFramework.buildKeyObject(); //static method call. 
    }
}

Can you guys help me with this?

Upvotes: 0

Views: 373

Answers (1)

metacubed
metacubed

Reputation: 7271

Constructor injection is one of the common ways to do this. It does require you to modify the class under test for easier testing.

First, instead of creating a new Helper in the method, make it a member variable and assign it in the constructor.

class A {

    private Helper helper;

    // constructor for test use
    public A(Helper helper) {
        this.helper = helper;
    }

    // convenience constructor for production use
    public A() {
        this(new Helper());
    }
}

Now, in your test, you can use the test constructor to inject any mock object derived from Helper. This can be done using Mockito or even simple inheritance.

class MockHelper extends Helper {

    // mocked methods here
}

class ATest {

    public A aInstance = new A(new MockHelper());

    // ...
}

Upvotes: 1

Related Questions