Reputation: 291
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
Upvotes: 17
Views: 30024
Reputation: 1
@PrepareForTest(Demo.class)
public class DemoTest {
@Rule
public PowerMockRule rule = new PowerMockRule()
@Before
public void setup(){
PowerMockAgent.initializeIfNeeded();
}
@Test
public void finalClassMock() {
final Demo demo = PowerMockito.mock(Demo.class);
PowerMockito.when(demo.myMethod()).thenReturn("something");
assertEquals("something", demo.myMethod());
}
}
or this way also works thanks @gontard
Upvotes: 0
Reputation: 29550
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());
}
}
Upvotes: 32