如何确定 Android-Espresso 测试用例的日期

How to fix the date for an Android-Espresso test case

这个问题是关于让Android测试用例独立于日期,当它们是运行时,即使被测试的内容依赖于phone/emulator的系统日期。

我想用 Espresso 在我的 Android 应用程序中测试一个视图,这取决于当前日期。它基本上是一个日历:我有一个 ListView,每天一行,我可以单击一天以获取当天的详细视图:

    <ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/toolbar"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:headerDividersEnabled="false"/>

但我的问题有趣的部分是 ActionBar:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/cp_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:showIn="@layout/activity_month_time_record">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Toolbar Title"
    android:layout_gravity="center"
    android:id="@+id/toolbar_title"
    style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/>

</android.support.v7.widget.Toolbar>

您在那里看到的 TextView 将显示所选日期的日期,例如 "Wed, 4. May '16"。当然,当加载月视图时,将显示当前月份。这使得测试取决于当前日期。当我表演

onData(anything()).inAdapterView(withId(android.R.id.list)).atPosition(5)
            .perform(click());

ActionBar 将显示 "Wed, 4. May '16",如果我 运行 这个测试是在 2016 年 5 月,但是 "Sat, 4. Jun '16",如果我 运行 这个测试是在 6 月2016.

So how do I tell Espresso to fix the Date for this test to a certain day?

我也有使用固定日期时间的需求。我的解决方案是创建一个包装器 class 来访问当前 date/time。这个 class 被设计为单例,在我的测试中,我用一个新实例替换了静态单例实例。这个新的配置为始终报告相同的 "current" date/time 并且可以更改为新的 date/time.