Use Mockito/Powermockito to Mock a Public Method of Super Class

Mockito How to mock only the call of a method of the superclass

No, Mockito does not support this.

This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:

Favor composition over inheritance

If you extract a strategy instead of extending a super class the problem is gone.

If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.

I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.

Can I mock a superclass's constructor with Mockito/Powermock?

To work around this apparent limitation, I refactored my code, replacing inheritance with delegation, and I think I've ended up with a better design anyhow since the inheritance wasn't really necessary.

The new code looks like this. Mind you the code for the question was simplified, so the real classes have much more functionality.

class S {
S() {
// Format user's hard drive, call 911, and initiate self-destruct
}
}

class T {
T(S s) {} // Now T "has an S" instead of "is an S"
}

class Test {
@Mock private S mockS;
new T(s); // T's call to super() should call the mock, not the destructive S.
}

For those interested, using Guice and Android, the test looks more like this:

class T {
T(Activity activity, S s) {}
}

class Test {
@Mock Activity activity;
@Mock S mockS;
injector = Guice.createInjector(new AbstractModule() {
@Override protected void configure() {
bind(Activity.class).toInstance(activity);
bind(S.class).toInstance(mockS);
}}
);
T t = injector.getInstance(T.class);
}

How to mock super reference (on super class)?

With Powermock you can replace or suppress methods, so it is possible to change the action done by BaseService.save(). You can also make methods to do nothing with suppressing. You can even suppress static initializer blocks.

Please read this blog entry of the Powermock authors. See chapter "Replacing".

UPDATE:

Suppress seems to work for me, but replace not. See the picture below:
enter image description here



Related Topics



Leave a reply



Submit