單元測試與 PowerMock

爲何進行單元測試

在咱們開發的app的時候,可能會出現一些邏輯問題是測試人員測試不到的,或者在測試前須要自測的時候,但願程序自動執行,這時候就須要使用單元測試的。使用單元測試,就會須要模擬一些類或者變量,這時咱們就須要使用PowerMock。javascript

使用PowerMock

咱們新建一個Android Studio工程,默認會在工程下生成以下三個文件夾:androidTest, main,test。main不用說了就是你的程序入口,androidTest是android特有的測試方法,這個後面會講。這裏主要說一下test,這個是測試java的相關程序,理論上任何java均可以利用這個進行測試。android也是java寫的,固然就也能夠進行測試。java

依賴

咱們首先須要讓工程依賴測試的相關庫。android

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile "org.mockito:mockito-all:1.6.1"
    testCompile 'org.powermock:powermock-module-junit4:1.6.1'
    testCompile 'org.powermock:powermock-module-junit4-rule:1.6.1'
    testCompile 'org.powermock:powermock-api-mockito:1.6.1'
    testCompile "org.powermock:powermock-classloading-xstream:1.6.1"

}複製代碼

爲何用testCompile,這是代表只有在運行test工程時,纔會依賴這些。若是對這裏的語法有什麼疑問,能夠參考我以前的文章Android工程gradle詳解api

開始測試

基本數據傳遞

咱們在MainActivity中寫一個方法,來判斷文件是否存在:app

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public boolean checkFile(File file){
        return  file.exists();
    }
}複製代碼

而後在上文中提到過的test文件夾下打開ExampleUnitTest,或者新建一個類均可以,添加以下方法:ide

public class ExampleUnitTest {

    @Test
    public void testEmpty() {
        File file = PowerMockito.mock(File.class);//模擬一個file文件
        MainActivity activity = new MainActivity();//新建一個這個類
        PowerMockito.when(file.exists()).thenReturn(true);//因爲file是模擬變量,那麼就要指定當調用模擬變量的某個方法時所返回的值
        Assert.assertTrue(activity.checkFile(file));//斷言,這個不用說了吧

    }
}複製代碼

而後右鍵點擊該文件,選擇運行:post


能夠看到運行成功,一切都是正確的。根據註釋能夠明白咱們的意圖,就是當 file.exists()返回true時,那麼這個方法也要返回true,我就認唔這個方法沒毛病。那若是方法出錯是什麼樣呢
那麼假設,咱們代碼寫錯了,咱們修改一下上面的代碼:

public boolean checkFile(File file){
     return  !file.exists();//故意寫錯
    }複製代碼

看看測試代碼能不能檢測出來,運行:單元測試


很明顯斷言錯了,咱們立刻就能發現對應問題。

新建對象

上面測試的對象是傳遞進來的,那麼咱們若是測試一個new的對象能夠嗎?固然也能夠:
代碼以下:測試

public boolean checkFileByPath(String path){
        File file = new File(path);
        return  file.exists();
    }複製代碼

測試代碼以下:gradle

@RunWith(PowerMockRunner.class)
public class ExampleUnitTest {

    @Test
    public void testEmpty() {
        File file = PowerMockito.mock(File.class);
        MainActivity activity = new MainActivity();
        PowerMockito.when(file.exists()).thenReturn(true);
        Assert.assertTrue(activity.checkFile(file));

    }
    @Test
    @PrepareForTest(MainActivity.class)
    public void testEmptyBypath() throws Exception {
        File file = PowerMockito.mock(File.class);
        MainActivity activity = new MainActivity();
        PowerMockito.whenNew(File.class).withArguments("path").thenReturn(file);//意思是當new File時返回模擬變量file
        PowerMockito.when(file.exists()).thenReturn(true);
        Assert.assertTrue(activity.checkFileByPath("path"));//傳入的變量與上面構建時一致,都要是path

    }
}複製代碼

注意當使用PowerMockito.whenNew方法時,必須加註解@PrepareForTest和@RunWith。註解@PrepareForTest裏寫的類是須要mock的new對象代碼所在的類。

模擬一個類中的final類型方法

首先咱們須要寫一個包含fina方法的類:

public class StringUtil {
   public final boolean isOk(){
       return true;
   }
}複製代碼

而後調用:

public boolean checkString(StringUtil util){

        return  util.isOk();
    }複製代碼

接着給出測試代碼:

@Test
    @PrepareForTest(StringUtil.class)
    public void testFinal() throws Exception {
        StringUtil util = PowerMockito.mock(StringUtil.class);
        MainActivity activity = new MainActivity();
        PowerMockito.when(util.isOk()).thenReturn(true);
        Assert.assertTrue(activity.checkString(util));

    }複製代碼

當須要mock final方法的時候,必須加註解@PrepareForTest和@RunWith。註解@PrepareForTest裏寫的類是final方法所在的類。

模擬靜態方法

給出靜態方法:

public class StringUtil {
   public final boolean isOk(){
       return true;
   }

    public static boolean isOkStatic(){
        return true;
    }
}複製代碼

給出調用:

public boolean checkStringByStatic(){

        return  StringUtil.isOkStatic();
    }複製代碼

測試代碼:

@Test
    @PrepareForTest(StringUtil.class)
    public void testStatic() throws Exception {
        MainActivity activity = new MainActivity();
        PowerMockito.mockStatic(StringUtil.class);
        PowerMockito.when(StringUtil.isOkStatic()).thenReturn(true);
        Assert.assertTrue(activity.checkStringByStatic());

    }複製代碼

當須要mock靜態方法的時候,必須加註解@PrepareForTest和@RunWith。註解@PrepareForTest裏寫的類是靜態方法所在的類。

模擬私有方法

咱們寫一個私有方法和調用:

public boolean checkStringPrivate(){

        return  isOkPrivate();
    }
    private  boolean isOkPrivate(){
        return true;
    }複製代碼

測試代碼:

@Test
    @PrepareForTest(MainActivity.class)
    public void testPrivate() throws Exception {
        MainActivity mainActivity = PowerMockito.mock(MainActivity.class);
        PowerMockito.when(mainActivity.checkStringPrivate()).thenCallRealMethod();
        PowerMockito.when(mainActivity, "isOkPrivate").thenReturn(true);//isOkPrivate是私有方法,可是模擬了MainActivity,能夠經過公有方法間接調用測試
        Assert.assertTrue(mainActivity.checkStringPrivate());

    }複製代碼

spy

當咱們想檢測一個類中變量的變化時能夠用這種方式:
好比咱們寫一個Spyer類:

public class Spyer {
    public int count = 0;
    public void onCreate(){
        count = 1;
    }
}複製代碼

咱們在測試的時候能夠這樣:

@Test
    public void testSpy() throws Exception {
       Spyer spyer = PowerMockito.spy(new Spyer());
      spyer.onCreate();
        Assert.assertEquals(1, spyer.count);


    }複製代碼

模糊匹配

當咱們想測試一個方法時,可能不想傳入某一個精確的值,這時候可使用Mockito.anyInt(),Mockito.anyString()

##

可能出現的問題

  • org.powermock.reflect.exceptions.FieldNotFoundException:
    junit和powermock版本衝突:
    能夠作以下修改:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile "org.mockito:mockito-all:1.6.1"
    testCompile 'org.powermock:powermock-module-junit4:1.6.1'
    testCompile 'org.powermock:powermock-module-junit4-rule:1.6.1'
    testCompile 'org.powermock:powermock-api-mockito:1.6.1'
    testCompile "org.powermock:powermock-classloading-xstream:1.6.1"

}複製代碼
  • 使用Powermock後會提示classloader錯誤
    加入註解:@PowerMockIgnore("javax.management.*")
相關文章
相關標籤/搜索