我有一个活动,可以根据web服务调用返回的状态显示不同的祝酒词。
我正在编写一个测试类,我的第一个测试是,当出现网络错误时,会显示其中一个祝酒词。以下是测试等级:
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest extends BaseTest {
@Rule
public final ActivityTestRule<LoginActivity> login = new ActivityTestRule(LoginActivity.class, true);
@Test
public void noNetwork() {
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
login.getActivity().onEventMainThread(new LoginResp(CopiaWebServiceClient.ResponseStatus.NETWORK_ERROR));
}
});
onView(withText(R.string.toast_no_network_connection))
.inRoot(withDecorView(not(is(login.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
}
所以
noNetwork
测试呼叫
LoginActivity
的
onEventMainThread(LoginResp loginResp)
方法(这需要在UI线程上运行,因此我使用
runOnMainSync
)具有网络错误状态,以提示其显示预期的toast\u no\u network\u连接toast。
此测试正常运行并成功通过。
这是我的问题
:
如果我在测试类中添加第二个测试,则第二个测试失败。这是第二次测试,
完全相同的
除了它将不同的错误状态传递给
onEventMainThread(LoginResp LoginResp)
因此,我们将展示一个不同的祝酒词:
@Test
public void serverErr() {
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
login.getActivity().onEventMainThread(new LoginResp(CopiaWebServiceClient.ResponseStatus.HTTP_SERVER_ERROR));
}
});
onView(withText(R.string.toast_operation_failure_app_error))
.inRoot(withDecorView(not(is(login.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
第二次测试失败,输出:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: <2131689669>[toast_operation_failure_app_error] value: Sorry, failure to complete operation due to application error.
然而,在运行测试的同时观看模拟器,我看到了
toast_no_network_connection
toast(第一个测试预期),然后是
toast_operation_failure_app_error
toast(第二次测试预期)。为什么第二次测试失败?
这与一个接一个地运行的测试有关,因为当我注释掉第一个测试时,第二个测试通过了。
我的
onEventMainThread(LoginResp LoginResp)
中的方法
登陆界面
具有以下代码,根据状态显示适当的toast:
switch (status) {
case HTTP_UNAUTHORIZED:
DialogCreator.createAlertDialog(this, getString(R.string.dialog_msg_login_fail)).show();
break;
case NETWORK_ERROR:
Toast.makeText(this, getString(R.string.toast_no_network_connection), Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(this, getString(R.string.toast_operation_failure_app_error), Toast.LENGTH_SHORT).show();
}
调试测试时,我看到第一个测试按预期进入NETWORK\u错误情况,第二个测试进入switch语句的
default
节,也如预期的那样。