reference for unit test
basic:
differences between Local unit test and Instrumentation Test:
Local unit test: can just run on JVM, doesn't need Android framework
Instrumentation Test: can test Android component(Activity, Service...) and UI
create Class for testing(both local unit test and instrumentation test) in app/src/androidTest/java/<package_name>
set build.gradle:
dependencies {
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test:runner:0.4'
// Set this dependency to use JUnit 4 rules
androidTestCompile 'com.android.support.test:rules:0.4'
androidTestCompile 'com.android.support:support-annotations:23.1.1'
}
mokito for mocking context seems useless if we use the sample code snippet here (the Context is null and MockitoAnnotations.initMocks can't work
sample Local unit test
import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class MyUnitTest { @Test public void testOne() { assertTrue("123".equals("123")); } }
sample Instrumentation test
import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.widget.Toast; //JUnit4 public class ActivityFunctionTest extends ActivityInstrumentationTestCase2{ public ActivityFunctionTest(Class activityClass) { super(activityClass); } public ActivityFunctionTest(){ super(MainMenuAcitivity.class); } public void testSetText() throws Exception { // set text getActivity().runOnUiThread(new Runnable() { @Override public void run() { MainMenuAcitivity activity = getActivity(); Toast.makeText(activity, "test toast 2", Toast.LENGTH_SHORT).show(); } }); getInstrumentation().waitForIdleSync(); } @UiThreadTest public void testSetTextWithAnnotation() throws Exception { MainMenuAcitivity activity = getActivity(); Toast.makeText(activity, "test toast", Toast.LENGTH_SHORT).show(); } }
monkey command:
adb shell monkey -p <package_name> -v <number_of_events>
沒有留言:
張貼留言