2

This question is about making Android test cases independent of the date, when they are run, even if the content being tested depends on the system date of the phone/emulator.

I want to test a view in my Android App with Espresso, that depends on the current date. It basically a calendar: I have a ListView with one row for each day and I can click onto a day to get a detail view for the day:

    <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"/>

But the interesting part for my question is the 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>

The TextView you see there will show the date of the selected day, for example "Wed, 4. May '16". Of course when the month view is loaded, the current month will be shown. That makes the test depending on the current date. When I perform

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

the ActionBar will show "Wed, 4. May '16", if I run this test in May 2016, but "Sat, 4. Jun '16", if I run this test in June 2016.

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

Ruik
  • 1,222
  • 1
  • 20
  • 36
  • You can't do this by espresso. Espresso is only a library for ui tests. For logic operations you should use another testing frameworks such as Mockito. – Artem Mostyaev May 13 '16 at 09:31

1 Answers1

1

I had the same needs to use a fixed date time. My solution was to create a wrapper class to access current date/time. This class is designed as singleton and in my test I replace the static singleton instance with a new one. This new one is configured to report always the same "current" date/time and can be changed to a new date/time.

nenick
  • 7,340
  • 3
  • 31
  • 23