用浓缩咖啡测试表盘 activity

Test dial activity with espresso

我正在尝试测试将用户发送到 Phone activity... 的按钮点击,如下所示:

public void callNumber(String number){
        Uri numberUri = Uri.parse("tel:"+number);
        Intent callIntent = new Intent(Intent.ACTION_DIAL, numberUri);
        startActivity(callIntent);
}

嗯...但是当我运行这个测试时:

    @Rule
public IntentsTestRule<HelpView> mActivityRule = new IntentsTestRule<>(HelpView.class, true, true);

@ClassRule
static public DeviceAnimationTestRule deviceAnimationTestRule = new DeviceAnimationTestRule();


    @Test
    public void clickDialButtonTest(){
        onView(withId(R.id.help_viewpager)).perform(swipeLeft());
        onView(withId(R.id.help_viewpager)).perform(swipeLeft());

        onView(withId(R.id.phone_call_btn)).perform(click());
        intended(allOf(hasAction(Intent.ACTION_DIAL)));
    }

我明白了:

想要匹配 1 个意图。实际匹配 0 个意图。

编辑:

实际上,Espresso 没有等待 ViewPager 中的切换完成。所以当按钮被点击时,什么也没有发生。我可以解决这个问题:

@Test
public void clickOnMapButtonTest() {
    onView(withId(R.id.help_viewpager)).perform(swipeLeft());
    onView(withId(R.id.help_viewpager)).perform(swipeLeft());

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        Assert.fail();
    }

    onView(withId(R.id.phone_call_btn)).perform(click());

    intended(allOf(hasAction(Intent.ACTION_DIAL), toPackage("com.android.dialer")));
}

但这看起来有点不对...也许有更好的方法。谁有更好的选择?

感谢任何帮助!

您可能正在使用 ActivityTestRule 而不是 IntentsTestRule

编辑:

你不应该使用 Thread.sleep(2000)..."waiting" 的 Espresso 方法正在使用 IdlingResourceHere's a simple explanation of you can follow.

使用IntentsTestRule时,Intents.init()会在activity创建后开始记录意图,Intents.release()会在activity后清除所有记录的意图】 完了。使用 IntentsTestRule 在这里是有问题的,因为 Intents.release()HelpView activity 完成并导航到 Dialer activity 之前清除所有记录的意图有机会用 intended.

验证意图

相反,您可以使用 ActivityTestRule 并在启动 activity 之前调用 Intents.init(),并在测试后调用 Intents.release(),如下所示:

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

@ClassRule
static public DeviceAnimationTestRule deviceAnimationTestRule = new DeviceAnimationTestRule();

    @Before
    public void setUp() {
       // start recording intents before activity launch
       Intents.init();
    }

    @After
    public void cleanUp() {
       // clears out all recorded intents after test completes
       Intents.release();
    }

    @Test
    public void clickDialButtonTest(){
        onView(withId(R.id.help_viewpager)).perform(swipeLeft());
        onView(withId(R.id.help_viewpager)).perform(swipeLeft());

        onView(withId(R.id.phone_call_btn)).perform(click());
        // now, we can verify Intent.Action Dial against the
        // list of recorded intents
        intended(allOf(hasAction(Intent.ACTION_DIAL)));
    }