如何在要使用PowerMock测试的模拟抽象类中存根父类方法调用

时间:2018-12-19 19:31:44

标签: java android unit-testing android-fragments powermock

这是我的课程结构

public abstract class MyTabFragment extends Fragment {


public void myMethod(final Parameter reason) {
    if (isAdded()) {
        getActivity().runOnUiThread(() -> {
            if (getActionDelegateHandler() != null) {
                getActionDelegateHandler().handleThis(reason.getMessageId());
            } else {
                Log.e(TAG, "no action handler");
            }
        });
    }
}

这是我的测试课。基本上,我想对myMethod()进行单元测试,该方法已调用其父Fragment类的“ iwego()”和“ getActivity()”调用。我想保留这些方法调用,但我不能。

@Test
public void testattempt() throws Exception {

    MyTabFragment testFragment = PowerMockito.mock(MyTabFragment.class);
    PowerMockito.doCallRealMethod().when(testFragment).myMethod(any(Parameter.class));

    when(testFragment.isAdded()).thenReturn(true); //This line throws error
    when(testFragment.getActivity()).thenReturn(fragmentActivity);
    when(testFragment.getActionDelegateHandler()).thenReturn(null);
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Runnable runnable = (Runnable) invocation.getArguments()[0];
            runnable.run();
            return null;
        }
    }).when(fragmentActivity).runOnUiThread(any(Runnable.class));


    testFragment.myMethod(mockParameter);
    //asserts here...
    //verify(testFragment).getActionDelegateHandler();
}

运行测试会在我嘲笑iwego()调用的行上引发错误。

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);
Or 'a static method call on a prepared class`
For example:
    @PrepareForTest( { StaticService.class }) 
    TestClass{
       public void testMethod(){
           PowerMockito.mockStatic(StaticService.class);
           when(StaticService.say()).thenReturn(expected);
       }
    }

Also, this error might show up because:
1. inside when() you don't call method on mock but on some other object.
2. inside when() you don't call static method, but class has not been prepared.

我该如何解决。我正在使用PowerMock。任何帮助表示赞赏。谢谢

1 个答案:

答案 0 :(得分:0)

没关系。我发现正常的模拟调用确实有效。问题是在我的setup()方法中,我取消了所有超类的调用。在模拟出我需要进行的唯一超级调用之后,对于其他测试,我便能够像往常一样模拟预期的方法。