Friday, March 10, 2017

#Android How to setup test environment with Robolectric

1. ADD dependencies

    testCompile 'org.mockito:mockito-core:1.10.19'
    testCompile "org.robolectric:robolectric:3.3.1"
    testCompile "org.robolectric:shadows-multidex:3.0"
    testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1'

2. Create Test Class for Activity 

if you have a activity at 'src/main/java/com.example.activity.SomeActivity', 
create test activity at 'src/test/java/com.example.activitySomeActivityTest'.

* Edit Run Configuration , if you use OSX or linu.



3. Write Test Code 


@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 22)
public class LoginActivityTest {

    private LoginActivity subject;
    private EditText editTextId;
    private EditText editTextPass;
    private Button buttonLogin;

    @Before
    public void setUp() throws Exception {
        subject = Robolectric.setupActivity(LoginActivity.class);
        editTextId = (WashEditText) subject.findViewById(R.id.layoutEmail);
        editTextPass = (WashEditText) subject.findViewById(R.id.layoutPw);
        buttonLogin = (Button) subject.findViewById(R.id.btnLogin);
        subject.loginCommunicator = mock(LoginCommunicator.class);
    }

    @Test
    public void loginWithoutEmail() throws Exception {
        buttonLogin.performClick();
        ShadowLooper.idleMainLooper();
        verify(subject.loginCommunicator, never()).requestLoginEmail(eq("liketaehoon@gmail.com"), eq(CommonUtil.password("1234")), anyString(), any(WashResponse.Listener.class));
        assertThat( ShadowToast.getTextOfLatestToast(), equalTo(subject.getString(R.string.error_input_email)));
    }
}
4. Run Test 

1 comment: