我需要模拟一些静态方法,到目前为止这很好,可以这样做:
@RunWith(PowerMockRunner.class)
@PrepareForTest({DataService.class})
public class PlayersAllViewModelTest {
// mock objects
private PlayersAllContextHandler mContextHandler;
private PlayersAllAdapter mAdapter;
@Before
public void setUp() throws Exception {
mockStatic(DataService.class);
//define mocks
mContextHandler = mock(PlayersAllContextHandler.class);
mAdapter = mock(PlayersAllAdapter.class);
}
@Test
public void check_init_requests_are_done() throws Exception {
// create instance of viewmodel
new PlayersAllViewModel(mContextHandler, mAdapter);
// check dataservice is requested for method 'getAllPlayers()'
PowerMockito.verifyStatic();
DataService.getAllPlayers(any(DataServiceCallback.class));
}
现在我需要测试回调中应答的给定响应(success()/ failure())的行为。正常的方法是这样的:
// define mock answer
doAnswer(new Answer<MyCallback<String>>() {
@Override
public MyCallback answer(InvocationOnMock invocation) throws Throwable {
MyCallback<Player> callback = (MyCallback<Player>) invocation.getArguments()[0];
callback.onFailure(new UnsupportedOperationException());
return null;
}
}).when(>>mocked class instance<<).myTestMethod(any(MyCallback.class));
因为想要调用静态方法,所以不能这样做。没有一个可以填补空白的类的模拟实例:(
有人知道这样做的正确方法是什么?