/
OpenFragmentRule.java
49 lines (43 loc) · 1.59 KB
/
OpenFragmentRule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.testing.rules;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;
import android.support.test.rule.ActivityTestRule;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import com.testing.common.ActivityUtils;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* A rule to be used for testing of a single fragment. Fragment will be opened before each test
* annotated with @Test and before methods annotated with @Before. During the duration of the test
* you will be able to manipulate Fragment directly.
*
* @param <A> - the activity to test.
*/
class OpenFragmentRule<A extends AppCompatActivity> implements TestRule {
private final ActivityTestRule<A> activityRule;
private final Fragment fragment;
private final int timeoutSec = 5;
/**
* Create fragment test rule, don't forget to add @Rule.
*
* @param activityRule - Activity Test Rule for starting fragment.
* @param fragment - fragment for opening.
*/
OpenFragmentRule(ActivityTestRule<A> activityRule, Fragment fragment) {
this.activityRule = activityRule;
this.fragment = fragment;
}
@Override
public Statement apply(Statement statement, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
ActivityUtils.openFragment(activityRule.getActivity(), fragment);
await().atMost(timeoutSec, SECONDS).until(fragment::isResumed);
statement.evaluate();
}
};
}
}