mercredi 24 mai 2017

How to mock Callback answer for static methods with PowerMock?

I need to mock some static methods, that's fine so far and can be done like this:

@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));

}

Now i need to test the behavior for a given response (success() / failure()) answered in a callback. The normal way to do so is like this:

    // 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));

Because is want to call a static method, i can't do it like that so. There's no mocked instance of a class that could fill the gap :(

Does anybody know what's the correct way to do it?

Aucun commentaire:

Enregistrer un commentaire