Android单元测试开始

时间:2016-07-18 12:31:38

标签: android unit-testing testing

我已阅读了很多文章,并尝试使用Roboelectric开始单元测试,但我仍然没有得到它并且无法编写简单的单元测试。 任何人都可以指导我使用什么以及如何开始,因为在Android中进行单元测试并不容易。

3 个答案:

答案 0 :(得分:2)

要使用robotium,请按照以下步骤操作:

1.-导入robotium - Build.gradle:

dependencies {
    ....
    testCompile 'junit:junit:4.12'
    .....
    compile 'com.jayway.android.robotium:robotium-solo:5.6.0'
    compile 'com.android.support:support-annotations:23.0.0'
    .....
}

2.-创建一个Abtract类来初始化androidTest包中的测试:

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;

import com.robotium.solo.Solo;


public abstract class AbstractSystemTestBase<T extends Activity> extends ActivityInstrumentationTestCase2<T> {

    public static final int WAIT_FOR_ACTIVITY_TIMEOUT = 30000;  
    public static final int WAIT_FOR_DIALOG_TIMEOUT = 30000;    
    public static final int WAIT_FOR_VIEW_TIMEOUT = 6000;   
    public static final int WAIT_FOR_TEXT_TIMEOUT = 6000;   
    public static final int STANDARD_WAIT_TIME = 30000;
    public static final int SHORT_WAIT_TIME = 5000;

    protected Solo solo;

    public AbstractSystemTestBase(Class<T> activityClass) {
        super(activityClass);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        solo = new Solo(getInstrumentation(), getActivity());
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
        solo.finishOpenedActivities();
    }


}

3.-创建扩展Abstract类的测试类(在androidTest包内):

public class TestMainMenu extends AbstractSystemTestBase<MainMenuActivity> {

    public TestMainMenu() {
        super(MainMenuActivity.class);
    }

    public void testMenu() throws InterruptedException {
        assertTrue("MainMenu Activity never started", solo.waitForActivity(MainMenuActivity.class, WAIT_FOR_ACTIVITY_TIMEOUT));
        //YOUR TESTS HERE

        //EXAMPLE:

         View view = solo.getView("main_menu_activity_iv_go_activity_one");
        solo.clickOnView(view);
        assertTrue("Activity one never started", solo.waitForActivity(Activity1.class, WAIT_FOR_ACTIVITY_TIMEOUT));


    }
}

4.-运行测试。右键单击您的测试类

答案 1 :(得分:2)

我也有同样的问题,因为我在android中获得了单元测试的模块。这是一个可以帮助你的简单例子。我尽力帮助你。你可以运行EmailValidatorTest类来查看测试结果。对于assert(JUnit),您可以关注Assert。这是XML。

string

这是我的MainActivity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F0F0F0"
android:orientation="vertical" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="@string/lbl_register"
    android:textAllCaps="true"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#176CEC"
    android:textStyle="bold" />

<EditText
    android:id="@+id/editText_email"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:ems="10"
    android:hint="@string/lbl_email_hint"
    android:inputType="textEmailAddress"
    android:padding="12dp" />

<EditText
    android:id="@+id/editText_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="1dp"
    android:background="#fff"
    android:ems="10"
    android:hint="@string/lbl_password_hint"
    android:inputType="textPassword"
    android:padding="12dp" />

<Button
    android:id="@+id/btn_signup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:background="#176CEC"
    android:text="@string/lbl_btn_signup"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#fff"
    android:textStyle="bold" />

}

这是我的EmailValidator类

package com.example.hassidiczaddic.unittesting;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.hassidiczaddic.unittesting.R;
public class MainActivity extends Activity {
private EditText emailEditText;
private EditText passEditText;
private Button btnsignup;
private EmailValidator mEmailValidator;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emailEditText = (EditText) findViewById(R.id.editText_email);
    passEditText = (EditText) findViewById(R.id.editText_password);
    // Setup field validators.
    mEmailValidator = new EmailValidator();
    emailEditText.addTextChangedListener(mEmailValidator);
    passEditText.addTextChangedListener(mEmailValidator);


btnsignup=(Button)findViewById(R.id.btn_signup);
    btnsignup.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {


            // Don't save if the fields do not validate.
            if (!mEmailValidator.isValid()) {
                emailEditText.setError("Invalid email or Password");
                Log.w("TAG", "Invalid email");
                return;
            }else
                Toast.makeText(MainActivity.this,"Satrun is dead",Toast.LENGTH_SHORT).show();
        }
    });




}

这是我的UnitTesting在android:

package com.example.hassidiczaddic.unittesting;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator implements TextWatcher {

/**
 * Email validation pattern.
 */
// validating email id
public static final Pattern EMAIL_PATTERN = Pattern.compile(
        "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                "\\@" +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                "(" +
                "\\." +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                ")+"
);

// validating password with retype password
private boolean isValidPassword(String pass) {
    if (pass != null && pass.length() > 6) {
        return true;
    }
    return false;
}

private boolean mIsValid = false;

public boolean isValid() {
    return mIsValid;
}

public static boolean isValidEmail(CharSequence email) {
    return email != null && EMAIL_PATTERN.matcher(email).matches();
}

public static boolean isValidPassword(CharSequence pass) {
    return pass != null && isValidPassword(pass);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable editableText) {
 mIsValid=isValidEmail(editableText);
    mIsValid=isValidPassword(editableText);
}
}

不要忘记将Gradle与以下内容联系起来:

package com.example.hassidiczaddic.unittesting;
import android.test.suitebuilder.annotation.SmallTest;
import org.junit.Test;
import static org.junit.Assert.*;
@SmallTest
public class EmailValidatorTest {
@Test
public void emailValidator_CorrectEmailSimple_ReturnsTrue() {
    assertTrue(EmailValidator.isValidEmail("name_@email.com"));
}

@Test
public void emailValidator_CorrectEmailSubDomain_ReturnsTrue() {
    assertTrue(EmailValidator.isValidEmail("name@email.co.uk"));
}

@Test
public void emailValidator_InvalidEmailNoTld_ReturnsFalse() {
    assertFalse(EmailValidator.isValidEmail("name@email"));
}

@Test
public void emailValidator_InvalidEmailDoubleDot_ReturnsFalse() {
    assertFalse(EmailValidator.isValidEmail("name@email..com"));
}

@Test
public void emailValidator_InvalidEmailNoUsername_ReturnsFalse() {
    assertFalse(EmailValidator.isValidEmail("@email.com"));
}

@Test
public void emailValidator_EmptyString_ReturnsFalse() {
    assertFalse(EmailValidator.isValidEmail(""));
}

@Test
public void emailValidator_NullEmail_ReturnsFalse() {
    assertFalse(EmailValidator.isValidEmail(null));
}


@Test
public void passwordValidator_NullPassword_ReturnsFalse(){
    assertFalse(EmailValidator.isValidPassword(null));

    //other testcases for passwords
}}

答案 2 :(得分:0)

你可以尝试Mockito。

使用Mockito进行Android单元测试 https://www.raywenderlich.com/174137/android-unit-testing-with-mockito

使用TestMe(Android Studio的IntelliJ插件可以非常轻松地生成单元测试代码)

TestMe https://plugins.jetbrains.com/plugin/9471-testme

为Java或Groovy中的源类自动生成单元测试。 没有更多样板!

功能

  • 使用JUnit 4/5,TestNG或Spock框架自动生成Java或Groovy测试代码
  • 自动生成Mockito模拟
  • 生成测试参数和断言语句

<强>快速入门: http://weirddev.com/testme/