* With the new AndroidJUnit runner you can run both JUnit3 and JUnit4 tests in a single test * suite. The {@link AndroidRunnerBuilder} which extends JUnit's * {@link AllDefaultPossibilitiesBuilder} will create a single {@link * TestSuite} from all tests and run them. */ @RunWith(AndroidJUnit4.class) @LargeTest public class CalculatorInstrumentationTest { /** * A JUnit {@link Rule @Rule} to launch your activity under test. This is a replacement * for {@link ActivityInstrumentationTestCase2}. *
* Rules are interceptors which are executed for each test method and will run before * any of your setup code in the {@link Before @Before} method. *
* {@link ActivityTestRule} will create and launch of the activity for you and also expose * the activity under test. To get a reference to the activity you can use * the {@link ActivityTestRule#getActivity()} method. */ @Rule public ActivityTestRule mActivityRule = new ActivityTestRule<>( CalculatorActivity.class); @Test public void noOperandShowsComputationError() { final String expectedResult = mActivityRule.getActivity().getString(R.string.computationError); onView(withId(R.id.operation_add_btn)).perform(click()); onView(withId(R.id.operation_result_text_view)).check(matches(withText(expectedResult))); } @Test public void typeOperandsAndPerformAddOperation() { performOperation(R.id.operation_add_btn, "16.0", "16.0", "32.0"); } @Test public void typeOperandsAndPerformSubOperation() { performOperation(R.id.operation_sub_btn, "32.0", "16.0", "16.0"); } @Test public void typeOperandsAndPerformDivOperation() { performOperation(R.id.operation_div_btn, "128.0", "16.0", "8.0"); } @Test public void divZeroForOperandTwoShowsError() { final String expectedResult = mActivityRule.getActivity().getString( R.string.computationError); performOperation(R.id.operation_div_btn, "128.0", "0.0", expectedResult); } @Test public void typeOperandsAndPerformMulOperation() { performOperation(R.id.operation_mul_btn, "16.0", "16.0", "256.0"); } private void performOperation(int btnOperationResId, String operandOne, String operandTwo, String expectedResult) { // Type the two operands in the EditText fields onView(withId(R.id.operand_one_edit_text)).perform(typeText(operandOne), closeSoftKeyboard()); onView(withId(R.id.operand_two_edit_text)).perform(typeText(operandTwo), closeSoftKeyboard()); // Click on a given operation button onView(withId(btnOperationResId)).perform(click()); // Check the expected test is displayed in the Ui onView(withId(R.id.operation_result_text_view)).check(matches(withText(expectedResult))); } }