單元測試與PowerMock

MarPetre 7年前發布 | 8K 次閱讀 單元測試 Java Android開發 移動開發

為什么進行單元測試

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

使用PowerMock

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

依賴

我們首先需要讓工程依賴測試的相關庫。

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"

}</code></pre>

為什么用testCompile,這是表明只有在運行test工程時,才會依賴這些。

開始測試

基本數據傳遞

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

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();
}

}</code></pre>

然后在上文中提到過的test文件夾下打開ExampleUnitTest,或者新建一個類都可以,添加如下方法:

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));//斷言,這個不用說了吧

}

}</code></pre>

然后右鍵點擊該文件,選擇運行:

可以看到運行成功,一切都是正確的。根據注釋可以明白我們的意圖,就是當 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();
    }

測試代碼如下:

@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

}

}</code></pre>

注意當使用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();
}</code></pre> 

接著給出測試代碼:

@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.*")

 

來自:http://www.jianshu.com/p/472649b5710f

 

 本文由用戶 MarPetre 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!