Android Testing — Timeouts

Radim Vaculík
1 min readNov 25, 2016

In our company, we try to write unit and integration/instrumentation tests for each component of the Android app. Unit tests are simple to write, because it’s basically Java-only test. It’s quick, short and lightweight. But on the other hand, there are lots of issues with Android instrumental tests — you need an emulator, which is pain itself. The runtime of instrumentation tests is longer in comparison to unit tests and also, there are some troubles with flaky tests.

One more problem are stuck tests. The default timeout for each test is 0L. So the test can be run indefinitely and your tests can’t be finished.

There are couple solutions how you can prevent this problem.

The first (and really nice) solution is to use timeout parameter in @Test annotation. The time is in milliseconds.

@Test(timeout=100)
public void myTestFunction() { ... }

The other solution is to use @Rule annotation. This is really handy if you want to setup timeout for the whole testcase (for every test in the file).

public class MyTests {

@Rule
public Timeout globalTimeout = Timeout.seconds(10);


@Test
public void test1() throws Exception {
...
}

@Test
public void test2() throws Exception {
...
}
}

If the timeout is reached, you’ll get TimeoutException.

--

--