2016-05-10 3 views
5

Ich muss eine einzelne Aktivität in meiner Android App testen. Die Dokumentation von ActivityInstrumentationTestCase2 sagt:ActivityInstrumentationTestCase2 vs ActivityTestRule

Diese Klasse bietet Funktionstests einer einzelnen Aktivität.

und die Dokumentation von ActivityTestRule sagt:

Diese Regel Funktionsprüfung einer einzigen Aktivität zur Verfügung stellt.

Fast die gleichen Worte. Neben den beiden Samples, die ich programmiert habe, mache ich das gleiche. Also sollte ich ActivityTestRule über ActivityInstrumentationTestCase2 oder umgekehrt bevorzugen?

Was ich sehe, ist, dass ActivityInstrumentationTestCase2 erstreckt wie ein (ist seine Vorfahren junit.framework.TestCase und Prüfverfahren sollte mit dem Wort test beginnen) JUnit3-Stil Test sucht.

Mit ActivityTestRule

package sample.com.sample_project_2; 

import android.support.test.rule.ActivityTestRule; 
import android.support.test.runner.AndroidJUnit4; 
import android.test.suitebuilder.annotation.LargeTest; 

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.typeText; 
import static android.support.test.espresso.matcher.ViewMatchers.withId; 

@RunWith(AndroidJUnit4.class) 
@LargeTest 
public class ApplicationTest { 

    @Rule 
    public ActivityTestRule<SecAct> mActivityRule = new ActivityTestRule(SecAct.class); 

    @Test 
    public void foo() { 
     onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE")); 

    } 
} 

Erweiterung ActivityInstrumentationTestCase2

package sample.com.sample_project_2; 

import android.test.ActivityInstrumentationTestCase2; 

import static android.support.test.espresso.Espresso.onView; 
import static android.support.test.espresso.action.ViewActions.typeText; 
import static android.support.test.espresso.matcher.ViewMatchers.withId; 


public class ApplicationTest2 extends ActivityInstrumentationTestCase2<SecAct> { 

    public ApplicationTest2() { 
     super(SecAct.class); 
    } 

    @Override 
    protected void setUp() throws Exception { 
     super.setUp(); 
     getActivity(); 
    } 


    public void testFoo2() { 
     onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE 2")); 

    } 
} 

Antwort

1

Für Ihr Beispiel gibt es keinen Unterschied. Sie können jeden von ihnen verwenden.

Gemäß OO-Prinzip werden wir "Zusammensetzung über Vererbung bevorzugen". Verwendung von ActivityTestRule<> ist durch Zusammensetzung, während ActivityInstrumentationTestCase2<> obwohl Vererbung ist.

Manchmal bevorzuge ich eine gemeinsame Basisklasse für meine Testklassen, um häufige Initialisierungen wiederzuverwenden. Dies hilft mir, Tests nach einem Thema zu gruppieren. ActivityTestRule<> erlaubt mir, solche Dinge zu tun.

Aus diesen Gründen bevorzuge ich ActivityTestRule<>. Ansonsten habe ich keinen Unterschied gesehen.

Verwandte Themen