本文主要介紹在android studio中進行單元測試的方式蜗顽,你將了解到
1.如何在android studio中引用JUnit4
2.單元測試Demo
然后在build.gradle中添加
compile 'com.jakewharton.espresso:espresso:1.1-r3'~~~
Demo
新建一個Calculator 測試它的方法
package com.example.news;
/**
-
Created by 小新 on 2016/7/1.
*/
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;
}public double addMore(double a,double b,double c){
return a+b+c;
}
}
在類名上面點擊右鍵生成test測試類
![測試類生成截圖](http://upload-images.jianshu.io/upload_images/796164-f98d82421be0796a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![測試類名种樱,勾選測試方法](http://upload-images.jianshu.io/upload_images/796164-5b982393d237fa2d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
會在測試類的包中自動生成測試類
package com.example.news;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
-
Created by 小新 on 2016/7/1.
*/
public class CalculatorTest {@Before
public void setUp() throws Exception {}
@Test
public void testSum() throws Exception {}
@Test
public void testSubstract() throws Exception {}
@Test
public void testDivide() throws Exception {}
@Test
public void testMultiply() throws Exception {}
@Test
public void testAddMore() throws Exception {}
}
然后進行測試
package com.example.news;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
-
Created by 小新 on 2016/7/1.
*/
public class CalculatorTest1 {
private Calculator calculator;@Before
public void setUp() throws Exception {
calculator = new Calculator();}
@Test
public void testSum() throws Exception {
//測試sum函數(shù),因為sum函數(shù)返回的是兩個數(shù)的合為3
//這里期望返回的值是9
//所以會報錯
assertEquals(9d,calculator.sum(1d,2d),0);
}@Test
public void testSubstract() throws Exception {}
@Test
public void testDivide() throws Exception {}
@Test
public void testMultiply() throws Exception {}
@Test
public void testAddMore() throws Exception {}
}
運行這個類哥桥,結果為報錯,這個時候我們就需要修改函數(shù)了
到這里我們JUnix的簡單測試就結束了