public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
Press the double green arrow to run all the tests or the single green arrow to run only one. (In this case there is only one test so they both do the same thing.)
它应该通过(只要 2 + 2仍然是 4当你读这个答案)。恭喜你,你刚完成了第一个测试!
自己做测试
Let's write our own test. First add this class to your main app project so that we have something to test:
public class MyClass {
public int add(int a, int b) {
return a + b;
}
}
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
MyClass myClass = new MyClass();
int result = myClass.add(2, 2);
int expected = 4;
assertEquals(expected, result);
}
}
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.myapp", appContext.getPackageName());
}
}
再按一次绿色按钮。
As long as you have a real device connected or the emulator set up, it should have started it up and run your app. Congratulations, you just ran your first instrumented test!