环境准备
在 .gradle中配置
defaultConfig {
testInstrumentationRunner “android.support.test.runner.AndroidJUnitRunner”
}
dependencies {
testCompile ‘junit:junit:4.12’
compile ‘com.android.support.test.espresso:espresso-core:2.2.2’
compile ‘com.android.support.test?0.5’
}
纯Java测试
1、测试类
public class JavaTextActivity {
private int date;
public void JavaTextActivity(){
}
public String sayHello(int now , String user){
date = now;
String tall = “Hi,”+user+"."+getGreeting();
return tall;
}
public String getGreeting() {
if(date == 1)
return "Happy new year!";
else if(date >1 && date<6)
return "Good morning!";
else if(date==6)
return "Good afternoon!";
else
return "Good night!";
}
}
2.测试步骤
选择 JavaTextActivity 类名 —> 右键 Go To ---->Test ---->Create New Test ----->选中 setUp@Before And tearDown@After ------> OK ------->生成测试类 JavaTextActivityTest
3.测试类
public class JavaTextActivityTest {
private JavaTextActivity javaTextActivity = null;
@Before
public void setUp() throws Exception {
javaTextActivity = new JavaTextActivity();
}
@After
public void tearDown() throws Exception {
javaTextActivity = null;
}
@Test
public void sayHello() throws Exception {
}
@Test
public void testSayHelloInTheMorning() throws Exception{
int date = 2;
String user = "煲约二";
String result = javaTextActivity.sayHello(date,user);
assertEquals(result,"Hi,煲约二.Good morning!");
}
}
4.运行测试类
在工程列表中选中 JavaTextActivityTest -------->右键 Run “JavaTextActivityTest ”
5.测试类中的方法
在Favorite 窗口中选中 JavaTextActivityTest 中的 testSayHelloInTheMorning()右键选中
Run
6.测试结果
assertEquals(result,“Hi,煲约二.Good morning!”);
if (result == “Hi,煲约二.Good morning!”)
正确结果 Process finished with exit code 0
else
错误结果