Let's say I have a non-final concrete class with a final method like the one below.
public class ABC {
public final String myMethod(){
return "test test";
}
}
is it possible to mock myMethod()
to return something else when it is called in junit
using Powermockito
? Thank you
Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.
PowerMock integrates with mocking frameworks like EasyMock and Mockito and is meant to add additional functionality to these – such as mocking private methods, final classes, and final methods, etc. It does that by relying on bytecode manipulation and an entirely separate classloader.
While Mockito can help with test case writing, there are certain things it cannot do viz:. mocking or testing private, final or static methods. That is where, PowerMockito comes to the rescue. PowerMockito is capable of testing private, final or static methods as it makes use of Java Reflection API.
Configure Mockito for Final Methods and ClassesBefore we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.
This works :
@RunWith(PowerMockRunner.class)
@PrepareForTest(ABC.class)
public class ABCTest {
@Test
public void finalCouldBeMock() {
final ABC abc = PowerMockito.mock(ABC.class);
PowerMockito.when(abc.myMethod()).thenReturn("toto");
assertEquals("toto", abc.myMethod());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With