假设我有一个非最终具体类,具有如下所示的最终方法。
public class ABC {
public final String myMethod(){
return "test test";
}
}
当使用
myMethod()
在 junit
中调用它时,是否可以模拟 Powermockito
返回其他内容?谢谢你
这有效:
@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());
}
}
@PrepareForTest(Demo.class)
public class DemoTest {
@Rule
public powerMockRule = 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());
}
}
或者这种方式也有效,谢谢
@gontard