单元测试能帮我们很快的找出bug,能够让我们在项目开发的前期就发现问题,以降低后期发现问题解决的成本。
如果你安装的是最新版本的AndroidStudio,那么它本身就会自带单元测试框架
在build.gradle里你会发现这个:
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
这就是我们所要利用的单元测试框架
public class Calculator {
//+
public double sum(double a, double b){
return a + b;
}
//-
public double substract(double a, double b){
return a-b;
}
//%
public double divide(double a, double b){
return a%b;
}
//*
public double multiply(double a, double b){
return a*b;
}
}
之后就能看到我们生成测试类,在里面加上断言来得到我们想要的结果。
package com.example.junittestdemo;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by D'Russel on 2017/7/31.
*/
public class CalculatorTest {
private Calculator mCalculator;
@Before
public void setUp() throws Exception {
mCalculator = new Calculator();
}
@Test
public void sum() throws Exception {
assertEquals(6d, mCalculator.sum(1d, 5d), 0);
}
@Test
public void substract() throws Exception {
assertEquals(1d, mCalculator.substract(5d, 4d), 0);
}
@Test
public void divide() throws Exception {
assertEquals(4d, mCalculator.divide(20d, 5d), 0);
}
@Test
public void multiply() throws Exception {
}
}
这个代码模拟的是一个输入框,一个文本框,一个按钮的组合动作,在输入框输入russel,点击按钮,会在文本框里显示”Hello,russel”
代码如下:sayHello为一个按钮绑定的点击事件。
public void sayHello(View v){
TextView textView = (TextView) findViewById(R.id.textView);
EditText editText = (EditText) findViewById(R.id.editText);
textView.setText("Hello," + editText.getText().toString()+"!");
}
测试类:
package com.example.junittestdemo;
import android.support.test.rule.ActivityTestRule;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.junit.Assert.*;
/**
* Created by D'Russel on 2017/7/31.
*/
public class MainActivityTest {
private static final String STRING_TO_BE_TYPED = "russel";
@Rule
public ActivityTestRule mActivityRule = new ActivityTestRule<>(
MainActivity.class);
@Test
public void sayHello() throws Exception {
onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); //给EditText自动输入russel
onView(withId(R.id.say_hello)).perform(click()); //自动点击按钮
String expectedText = "Hello," + STRING_TO_BE_TYPED + "!";
onView(withId(R.id.textView)).check(matches(withText(expectedText))); //对TextView 内容和刚刚输入的内容进行匹配
}
}
执行测试用例
这个过程是需要模拟器或者真机测试的,不过不需要开发者手动去点击,它会自动执行这一过程。
然后我们发现这个用例执行成功
这养就完成了一个简单的有UI交互的单元测试