Shashi Ranjan
Shashi Ranjan

Reputation: 1561

Mock overridden method using mockito powermokito

I want to test my Service class method testB1Method2 by mocking overridden method a1Method2 of class B1. I do not want to change anything in class A1 and B1. I am using mockito 1.9.0 and powermockito 1.4.12. The following code I am trying:

UnitTestService class:

import static org.mockito.Mockito.*;

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.testng.Assert;
import org.testng.annotations.Test;

public class UnitTestService {

    @Mock
    B1 b1;
    @InjectMocks
    Service service = new Service();

    @Test
    public void testB1Method2() throws Exception {
        MockitoAnnotations.initMocks(this);
        when(b1.a1Method2()).thenReturn("mockvalue");
        PowerMockito.whenNew(B1.class).withArguments(Mockito.any()).thenReturn(b1);
        String output = service.serviceMethod();
        System.out.println("=====" + output);
        Assert.assertTrue("mockvalue".equalsIgnoreCase(output), "testA1Method2 failed!");
    }

}

Service class:

public class Service {

    public String serviceMethod() {
        B1 b1 = new B1("some data");
        return b1.a1Method2();
    }

}

class A1:

public abstract class A1 {

    public A1(String data) {
        //doing many thing with data
    }

    public String a1Method1() {
        return "from a1Method1";
    }

    public String a1Method2() {
        return "from a1Method2";
    }

}

B1 class:

public class B1 extends A1 {

    public B1(String data) {
        super(data);
    }

    @Override
    public String a1Method1() {
        return "a1Method1 from B1 class";
    }

}

I am running class UnitTestService using testNG in eclipse. And here actual method in class B1 a1Method2 is getting called as it is printing "=====from a1Method2" in console. ie: here it seems mockito is not able to mock this method.

What code change should I make in UnitTestService class to mock class B1 a1Method2 ?

Upvotes: 1

Views: 11065

Answers (1)

GhostCat
GhostCat

Reputation: 140613

You created hard to test code there, for absolutely no good reason. What is breaking your neck is that small little call to new B1 in your service class.

If you would be using dependency injection for that object; then you would absolutely not need to deal with powermock and mocking inherited methods. Because then you could simply create a "mock" B1; pass that to your service; and then you have full control over what will be happening during your test.

So, the viable alternative here might be to avoid complex test setup by simply improving your production code to be easier to test.

Watch those videos to better understand what I am talking about!

Upvotes: 0

Related Questions