2016-07-18 137 views
1

我已經閱讀了很多文章,並嘗試使用Roboelectric開始一個單元測試,但我仍然沒有得到它,我不能寫一個簡單的單元測試。 任何人都可以指導我使用什麼以及如何開始,因爲在Android中進行單元測試並不容易。Android單元測試開始

+0

你檢查自己的網站教程? – Lawrance

+0

https://developer.android.com/training/testing/start/index.html –

+0

@Lawrance是的,我檢查了網站的教程,仍然無法有一個明確的想法 –

回答

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.-創建您的擴展抽象類的測試類(在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.-運行你的測試。右鍵點擊你的測試類

+0

你可以舉一個例子如何測試我寫在某個類的方法嗎? –

+0

取決於該方法。在你有一個數學類有一個除法的情況下,這段代碼的工作原理如下: SimpleMath mSimpleMath = new SimpleMath(); int result = mSimpleMath.divide(4,2); assertTrue(「result failed!」,result == 2);儘管我認爲使用JUnit更好地處理這種場景 –

+0

,該方法需要一些參數並返回一個對象。 我的意思是我如何從測試引用到我想測試的指定方法 –

2

我也有同樣的問題,因爲我被授予模塊在Android單元測試。這是一個簡單的例子,可以幫助你。我盡我所能幫助你。你可以運行EmailValidatorTest類來查看測試結果。對於斷言(JUnit),您可以按照Assert。這是XML。

<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" /> 

這是我的MainActivity

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(); 
     } 
    }); 




} 

}

這是我爲EmailValidator類

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); 
} 
} 

這是我的單元測試Android中:

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("[email protected]")); 
} 

@Test 
public void emailValidator_CorrectEmailSubDomain_ReturnsTrue() { 
    assertTrue(EmailValidator.isValidEmail("[email protected]")); 
} 

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

@Test 
public void emailValidator_InvalidEmailDoubleDot_ReturnsFalse() { 
    assertFalse(EmailValidator.isValidEmail("[email protected]")); 
} 

@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 
}} 

不要忘了給您的SYC搖籃:

// Required -- JUnit 4 framework 
testCompile 'junit:junit:4.12' 
+0

感謝我投了你的答案 –

+1

這是我的榮幸,能夠有所幫助。我遇到了和你一樣的類似問題,並且找不到解決方案。如果我對這些話題很熟悉,我會隨時提供幫助。如果您認爲這有助於您理解,請將答案標爲正確。 :) :) – Niroj

+0

你好,謝謝你的努力,但我已經在你的答案之前接受了上述答案,所以我只能投票你的答案 –