【发布时间】: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;
}
【问题讨论】: