@@ -179,10 +179,93 @@ public class HamcrestTest {
179179```
180180
181181### Rules
182+
183+ ``` java
184+ public class CalculatorWithTestName {
185+
186+ @Rule
187+ public TestName name = new TestName ();
188+
189+ @Test
190+ public void testAdd () {
191+ Calculator calculator = new Calculator ();
192+ int total = calculator. add(4 , 5 );
193+ assertEquals(name. getMethodName() + " adding incorrectly" , 9 , total);
194+ }
195+
196+ @Test
197+ public void testDiff () {
198+ Calculator calculator = new Calculator ();
199+ int total = calculator. diff(12 , 7 );
200+ assertEquals(name. getMethodName() + " subtracting incorrectly" , 5 , total);
201+ }
202+ }
203+ ```
204+
182205### Categories
183206
184207## Android
185208### Android instrumented tests
209+
210+ ``` java
211+ public class MainActivityTestRule <A extends Activity > extends ActivityTestRule<A > {
212+
213+ public MainActivityTestRule (Class<A > activityClass ) {
214+ super (activityClass);
215+ }
216+ @Override
217+ protected Intent getActivityIntent () {
218+ Log . e(" MainActivityTestRule" , " Prepare the activity's intent" );
219+ return super . getActivityIntent();
220+ }
221+
222+ @Override
223+ protected void beforeActivityLaunched () {
224+ Log . e(" MainActivityTestRule" , " Execute before the activity is launched" );
225+ super . beforeActivityLaunched();
226+ }
227+
228+ @Override
229+ protected void afterActivityLaunched () {
230+ Log . e(" MainActivityTestRule" , " Execute after the activity has been launched" );
231+ super . afterActivityLaunched();
232+ }
233+
234+ @Override
235+ protected void afterActivityFinished () {
236+ Log . e(" MainActivityTestRule" , " Cleanup after it has finished" );
237+ super . afterActivityFinished();
238+ }
239+
240+ @Override
241+ public A launchActivity (Intent startIntent ) {
242+ Log . e(" MainActivityTestRule" , " Launching the activity" );
243+ return super . launchActivity(startIntent);
244+ }
245+ }
246+ ```
247+
248+ ``` java
249+
250+ @RunWith (AndroidJUnit4 . class)
251+ public class MainActivityTest {
252+
253+ @Rule
254+ public MainActivityTestRule<MainActivity > mainActivityActivityTestRule = new MainActivityTestRule<MainActivity > (MainActivity . class);
255+
256+ @Test
257+ public void testUI () {
258+ Activity activity = mainActivityActivityTestRule. getActivity();
259+ assertNotNull(activity. findViewById(R . id. text_hello));
260+ TextView helloView = (TextView ) activity. findViewById(R . id. text_hello);
261+ assertTrue(helloView. isShown());
262+ assertEquals(" Hello World!" , helloView. getText());
263+ assertEquals(InstrumentationRegistry . getTargetContext(). getString(R . string. hello_world), helloView. getText());
264+ assertNull(activity. findViewById(android. R . id. button1));
265+ }
266+ }
267+ ```
268+
186269### Android test rules
187270### Test filtering
188271### Espresso
0 commit comments