Reputation: 584
Is there any reason why Powermock wouldn't mock static method call and instead call the initial method within then() statement?
Here's the case where I have a chain of method calls:
TestClass method -call-> Class1 method -call-> Class2 static method -call-> Class3 static method -call-> Class4 method.
Class4 method tries to lookup an object that doesn't exist in context and hangs so I'm trying to mock public static Class3 method with Powermock.
All classes and methods are non-final. I use TestNg. My testMethod has a @PrepareForTest I tried the following ways to mock a method call:
PowerMockito.mockStatic(Class3.class);
when(Class3.callEvilMethod()).thenReturn("test");
OR instead of when-thenReturn:
doReturn("test").when(Class3.callEvilMethod());
OR
doAnswer(new Answer() {methos that returns test"}).when(Class3.callEvilMethod());
OR
PowerMockito.stub(PowerMockito.method(Class3.class, "callEvilMethod")).toReturn("test");
But when I run tests the initial Class3.callEvilMethod() gets called within when statement. And I have no idea why. Shouldn't it be mocked?
EDIT: I adapted my test to show you how it looks like:
@PrepareForTest( { Class1.class, Class2.class, Class3.class})
public class TestClass extends AbstractTest {
private Class1 class1;
@BeforeMethod
public void setUp() throws Exception {
class1 = new Class1() {
}
@Test
public void testMethod() throws Exception {
// Create various objects in Db, do other method calls, then:
PowerMockito.mockStatic(Class3.class);
// PowerMockito.suppress(PowerMockito.method(Class3.class, "evilMethod"));
// PowerMockito.when(Class3.EvilMethod()).thenReturn("test");
// doReturn("test").when(Class3.evilMethod());
// PowerMockito.stub(PowerMockito.method(Class3.class, "evilMethod")).toReturn("test");
class1.callMethod();
}
}
Upvotes: 1
Views: 857