如何在我要使用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(),该求解其父片片段'isadded()和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();
}

在我嘲笑ISADDED()调用的线路上运行测试引发错误。

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。任何帮助都将受到赞赏。谢谢

没关系。我发现普通模拟电话确实有效。问题在于,在我的设置()方法中,我都抑制了所有超级班级的呼叫。在嘲笑我唯一需要的超级呼叫之后,对于其他测试,我能够照常嘲笑我的预期方法。

最新更新