作为UI测试的一部分,在Application类中进行模拟API调用

问题描述 投票:1回答:1

背景:

我们的Android应用程序onCreate启动了一些初始化用例,它们执行了一些网络API调用。

同时启动我们的LAUNCHER活动。

在我们的UI测试中,我们使用MockWebServer存根API响应,并使用ANDROIDX_TEST_ORCHESTRATOR 1.1.1

问题:

在涉及主要活动的UI测试中,我们希望从测试中为初始化API调用添加不同的响应。

换句话说,每个测试都应该能够指定初始化API调用返回的响应。

但是,由于初始化服务在活动之前启动,并且UI测试中的所有代码在应用程序启动后运行。我们无法影响在此之前发生的响应。

问题:

是否可以像在Activity中使用ActivityTestRule一样从测试中手动启动应用程序?这将使我们能够根据测试的需求对初始化API调用进行存根,然后启动应用程序。

android mocking android-espresso android-testing mockwebserver
1个回答
0
投票

如果您查看ActivityTestRule文档:

ActivityTestRule (Class<T> activityClass, 
                boolean initialTouchMode, 
                boolean launchActivity)

因此您可以将false参数设置为launchActivity

@Rule
public final ActivityTestRule<ActivityToTest> mActivityRule = 
    new ActivityTestRule<>(ActivityToTest.class, true, false);

并在测试开始时执行所需的操作,然后在需要的时候启动活动,并以null作为参数:

mActivity = mActivityRule.launchActivity(null);

或者在需要时提供所需的附加内容:

Intent intent = new Intent();
intent.putExtra("your_key", "your_value");
mActivity = mActivityRule.launchActivity(intent);
© www.soinside.com 2019 - 2024. All rights reserved.