如何在浓缩咖啡中从另一个启动一个活动测试用例

时间:2016-10-04 11:24:32

标签: android android-espresso

我是Espresso的新手。我正在为Android应用程序编写测试用例。 我的问题是如何从First活动中启动第二个活动的测试用例。

第一次激活的测试用例如下

    package venki.estest;


import android.support.annotation.StringRes;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.widget.EditText;

import com.squareup.spoon.Spoon;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.isDialog;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;


/**
 * Created by ${venkie} on ${28/1/16}.
 */

@RunWith(AndroidJUnit4.class)
public class Login {
    private MainActivity mActivity;



    @Rule
    public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(MainActivity.class,true);
    private static final String URL = "https://api.myjson.com/bins/4v3nc;";
    private static final String EXPECTED="{\"Hello\":\"qwworld\"}";
    @Before
    public void setUp() {
        mActivity = activityTestRule.getActivity();
    }

    @Test
    public void emailIsInvalid() {
       // Spoon.screenshot(mActivity, "initial_state");
        onView(withId(R.id.user_name)).perform(typeText("invalid"), closeSoftKeyboard());
        onView(withId(R.id.submit)).perform(click());
        onView(withId(R.id.user_name)).check(matches(withError(getString(R.string.error_invalid_email))));
      //  Spoon.screenshot(mActivity, "after_login");
    }


    @Test
    public void emailIsEmpty() {
        Spoon.screenshot(mActivity, "initial_state");
        onView(withId(R.id.user_name)).perform(typeText(""),closeSoftKeyboard());
        onView(withId(R.id.submit)).perform(click());
        onView(withId(R.id.user_name)).check(matches(withError(getString(R.string.error_field_required))));
        Spoon.screenshot(mActivity, "after_login");
    }
    @Test
    public void passwordIsEmpty() {
        Spoon.screenshot(mActivity, "initial_state");

        onView(withId(R.id.user_name)).perform(typeText("email@email.com"), closeSoftKeyboard());
        onView(withId(R.id.password)).perform(clearText());
        onView(withId(R.id.submit)).perform(click());
        onView(withId(R.id.password)).check(matches(withError(getString(R.string.error_field_required))));
        Spoon.screenshot(mActivity, "after_login");

    }

    @Test
    public void passwordIsTooShort() {
        Spoon.screenshot(mActivity, "initial_state");

        onView(withId(R.id.user_name)).perform(typeText("email@email.com"), closeSoftKeyboard());
        onView(withId(R.id.password)).perform(typeText("1234"), closeSoftKeyboard());
        onView(withId(R.id.submit)).perform(click());
        onView(withId(R.id.password)).check(matches(withError(getString(R.string.error_invalid_password))));
        Spoon.screenshot(mActivity, "after_login");

    }
    @Test
    public void checkDeviceRegistered() throws IOException {

      //  Spoon.screenshot(mActivity, "initial_state");

        onView(withId(R.id.user_name)).perform(typeText("omoto.test1@gmail.com"));
        onView(withId(R.id.password)).perform(typeText("password"));
        onView(withId(R.id.submit)).perform(click());
        String response = calltoBackend();
        try {
            JSONObject responseObject = new JSONObject(response);
            String resString = responseObject.getString("status");
            if (resString.equalsIgnoreCase("NODEVICENAME")){
                onView(withText(R.string.my_title))
                        .inRoot(isDialog()) // <---
                        .check(matches(isDisplayed()));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
       /* OkHttpClient client=new OkHttpClient.Builder().build();
        okhttp3.Request request=new Request.Builder().url(URL).build();
        Response response=client.newCall(request).execute();

        Assert.assertEquals(EXPECTED, response.body().string());*/
       // Spoon.screenshot(mActivity, "after_login");

    }

    @Test
    public void zlaunch(){

        onView(withId(R.id.next)).perform(click());
        // here i want to launch test cases of Second Activity(i.e. Test2)

    }

    @Test
    public void wrongUserId() throws IOException {

        //  Spoon.screenshot(mActivity, "initial_state");

        onView(withId(R.id.user_name)).perform(typeText("omoto.test11@gmail.com"));
        onView(withId(R.id.password)).perform(typeText("password"));
        onView(withId(R.id.submit)).perform(click());
        String response = calltoBackend();
        try {
            JSONObject responseObject = new JSONObject(response);
            String resString = responseObject.getString("status");
            if (resString.equalsIgnoreCase("TABLOGINFAILED")){
                onView(withText(R.string.my_title2))
                        .inRoot(isDialog()) // <---
                        .check(matches(isDisplayed()));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
       /* OkHttpClient client=new OkHttpClient.Builder().build();
        okhttp3.Request request=new Request.Builder().url(URL).build();
        Response response=client.newCall(request).execute();

        Assert.assertEquals(EXPECTED, response.body().string());*/
        // Spoon.screenshot(mActivity, "after_login");

    }

    private String calltoBackend() {
        String response = null;
        JSONObject obj1 = new JSONObject();
        String uid = "000000000000001";
        try {
            obj1.put(Constants.PROCESS_ID, Constants.LogInId);
            obj1.put(Constants.IMEI_ID, uid);

            //obj1.put("azureprocessid", 10);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject obj2 = new JSONObject();
        try {
            // Constants.REG_ID = "012324354355231235435341";
           /* if (regid.equalsIgnoreCase("")){

                regid = gcMutls.getRegid();
            }*/
            obj2.put(Constants.EMAIL, "omoto.test1@gmail.com");
            obj2.put(Constants.PASSWORD, "password");
            obj2.put("googleid", Constants.REG_ID);

            //obj2.put("serverkey","AIzaSyBe9FFZm0v8rcT2OZw8bjtwksM5KOIJHDg");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        OkHttpClient client=new OkHttpClient.Builder().build();
        RequestBody formBody = new FormBody.Builder()
                .add(Constants.JSON_HEADER,obj1.toString())
                .add(Constants.JSON_BODY,obj2.toString())
                .build();

        okhttp3.Request request=new Request.Builder().url(Constants.BASE_URL).post(formBody).build();
        try {
            Response response1=client.newCall(request).execute();
            response = response1.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;

    }

    /*@Test
    public void loginFailed() {
        onView(withId(R.id.user_name)).perform(typeText("incorrect@email.com"), closeSoftKeyboard());
        onView(withId(R.id.password)).perform(typeText("123456"), closeSoftKeyboard());
        onView(withId(R.id.submit)).perform(click());
        onView(withText(getString(R.string.error_login_failed)))
                .inRoot(withDecorView(not(activityTestRule.getActivity().getWindow().getDecorView())))
                .check(matches(isDisplayed()));
    }*/


  /*



    @Test
    public void loginSuccessfully_shouldShowWelcomeMessage() {
        onView(withId(R.id.user_name)).perform(typeText("user@email.com"), closeSoftKeyboard());
        onView(withId(R.id.password)).perform(typeText("123456"), closeSoftKeyboard());
        onView(withId(R.id.submit)).perform(click());
     //   onView(withId(R.id.tv_welcome)).check(matches(withText("Hi user@email.com!")));
    }

    @Test
    public void loginSuccessfully_shouldShowToast() {
        onView(withId(R.id.user_name)).perform(typeText("user@email.com"), closeSoftKeyboard());
        onView(withId(R.id.password)).perform(typeText("123456"), closeSoftKeyboard());
        onView(withId(R.id.submit)).perform(click());
        onView(withText(getString(R.string.login_successfully)))
                .inRoot(withDecorView(not(activityTestRule.getActivity().getWindow().getDecorView())))
                .check(matches(isDisplayed()));
    }*/

    private String getString(@StringRes int resourceId) {
        return activityTestRule.getActivity().getString(resourceId);
    }

    private static Matcher<View> withError(final String expected) {
        return new TypeSafeMatcher<View>() {


            @Override
            public void describeTo(Description description) {
                description.appendText("Not found error message" + expected + ", find it!");
            }

            @Override
            protected boolean matchesSafely(View item) {
                if (item instanceof EditText) {
                    return ((EditText)item).getError().toString().equals(expected);
                }
                return false;
            }
        };
    }


}

第二活动(Test2)的测试用例如下:

  package venki.estest;

import android.support.annotation.StringRes;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.widget.EditText;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;

/**
 * Created by ${venkie} on ${28/1/16}.
 */
@RunWith(AndroidJUnit4.class)
public class Test2 {

    private MainActivity mActivity;
    @Rule
    public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(MainActivity.class, true,false);

    @Before
    public void setUp() {
        mActivity = activityTestRule.getActivity();
    }

    @Test
    public void emailIsInvalid() {
        // Spoon.screenshot(mActivity, "initial_state");
        onView(withId(R.id.user_name)).perform(typeText("invalid"), closeSoftKeyboard());
        onView(withId(R.id.submit)).perform(click());
        onView(withId(R.id.user_name)).check(matches(withError(getString(R.string.error_invalid_email))));
        //  Spoon.screenshot(mActivity, "after_login");
        Test3 test3 = new Test3();
        test3.emailIsInvalid();
    }

    private static Matcher<View> withError(final String expected) {
        return new TypeSafeMatcher<View>() {


            @Override
            public void describeTo(Description description) {
                description.appendText("Not found error message" + expected + ", find it!");
            }

            @Override
            protected boolean matchesSafely(View item) {
                if (item instanceof EditText) {
                    return ((EditText) item).getError().toString().equals(expected);
                }
                return false;
            }
        };

    }

    private String getString(@StringRes int resourceId) {
        return activityTestRule.getActivity().getString(resourceId);
    }

}

1 个答案:

答案 0 :(得分:0)

为什么你会两次测试同样的东西?

即使您愿意,我认为从另一个测试方法中手动调用测试方法(相同或其他活动)也不是一个好方法。这就是为什么这些首先是单独的测试。

但是,您可以将Test2的测试代码包含在ztest方法中,如下所示:

@Test
public void zlaunch(){
    onView(withId(R.id.next)).perform(click());
    // here instead of launching test cases of Second Activity
    // you can copy/paste the same code from Test2 again as below

    // Spoon.screenshot(mActivity, "initial_state");
    onView(withId(R.id.user_name)).perform(typeText("invalid"),closeSoftKeyboard());
    onView(withId(R.id.submit)).perform(click());
    //and so on
}