【问题标题】:Mocked method doesn't return expected value模拟方法不返回预期值
【发布时间】:2017-01-26 19:23:15
【问题描述】:

我想使用 Mockito 测试我的班级的一个方法。

public class SplashPresenter {
    public volatile State mField1 = State.DEFAULT;
    public volatile State mField2 = State.DEFAULT;

    boolean stateFlagsAreAllCompleted(@NonNull final ISplashView view) {
        if (mField1 == State.COMPLETE //
                && mField2 == State.COMPLETE) {

            // Check Forced Update
            final int updateCheckResult = checkForcedUpdate(); // <===
            if (updateCheckResult == MyConstants.PRODUCTION_UPDATE_AVAILABLE) {
                view.displayForcedUpdateAlert(false);
                return true;
            }

            if (updateCheckResult == MyConstants.BETA_UPDATE_AVAILABLE) {
                view.displayForcedUpdateAlert(true);
                return true;
            }

            view.restartLoader();
            // Move to the home screen
            return true;
        }

        return false;
    }

    int checkForcedUpdate() {
    ...... // my codes
    }
}

这是我的测试课:

public class SplashPresenterTest_ForStateFlags {

    private Context mContext;
    private ISplashView mView;

    @Before
    public void setUp() throws Exception {
        mContext = Mockito.mock(Context.class);
        mView = Mockito.mock(ISplashView.class);
    }

    @Test
    public void stateFlagsAreAllCompleted() throws Exception {
        SplashPresenter presenter = Mockito.mock(SplashPresenter.class);
        presenter.mField1 = State.COMPLETE;
        presenter.mField2 = State.COMPLETE;

        when(presenter.checkForcedUpdate()).thenReturn(1);

        boolean actual = presenter.stateFlagsAreAllCompleted(mView);
        System.out.println("actual: " + actual + ", " +
                presenter.mField1 + ", " +
                presenter.checkForcedUpdate());
        assertTrue(actual);
    }
}

测试失败是最后发生的事情。这是输出:

实际:假,完成,1

我不明白的是,即使我将stateFlagsAreAllCompleted 方法更改为以下代码,但仍然测试失败并显示上述输出。

boolean stateFlagsAreAllCompleted(@NonNull final ISplashView view) {

    return true;
}

【问题讨论】:

    标签: android mockito mvp


    【解决方案1】:

    您还没有模拟stateFlagsAreAllComplete 方法的行为。你需要做的:

    when(presenter.stateFlagsAreAllComplete(Matchers.any()).thenReturn(true);
    

    您可以将 Matchers.any() 参数微调为所需的类类型。

    编辑:我看到您正在尝试测试方法stateFlagsAreAllComplete。由于您正在尝试测试 SplashPresenter 类的方法 stateFlagsAreAllComplete,因此您不能通过模拟其方法正在测试的类来做到这一点。您将不得不使用该类的一个实例。模拟方法只能在测试时在另一个被测方法中调用时使用。

    您必须创建要测试的类的实例。

    【讨论】:

    • 其实我想测试stateFlagsAreAllComplete()的输出基于不同的条件(在方法内部设计的)。因此,通过这种方式,我无法评估输出。
    • 我现在看到了这个问题 - 您正在模拟您正在测试其方法的类。你不应该嘲笑被测类(违背了测试的目的)。您应该只模拟依赖项。创建该类的一个实例,然后对其进行测试。我更新我的答案
    • 啊,我不知道。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    相关资源
    最近更新 更多