配置同時使用PowerMock和Robolectric對Android進行單元測試


Robolectric官網上給了一個 配置教程,但是我使用它的方法進行配置,發現 使用 Mockito.spy函數的時候會出現Exception。
后來在PowerMock官網上找到了 另外一個教程,里面說使用PowerMockRule是不靠譜的,要使用PowerMock 1.6.0引入的新的@PowerMockRunnerDelegate annotation來進行配置
 
具體配置文件如下:
module里面的build.gradle添加依賴: 
 1 dependencies {
 2     ......
 3 
 4     testCompile "org.robolectric:robolectric:3.0"
 5     testCompile 'org.mockito:mockito-core:1.10.19'
 6     testCompile 'junit:junit:4.12'
 7     testCompile "org.powermock:powermock-module-junit4:1.6.4"
 8     testCompile "org.powermock:powermock-module-junit4-rule:1.6.4"
 9     testCompile "org.powermock:powermock-api-mockito:1.6.4"
10     testCompile "org.powermock:powermock-classloading-xstream:1.6.4"
11 }
 
對下面的 RobolectricTest 基類進行繼承,就可以正常使用PowerMock和Robolectric進行測試了
 
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
/**
 * Base class extended by every Robolectric test in this project.
 * <p/>
 * You can use Powermock together with Robolectric.
 */
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class,
        sdk = 21)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
public abstract class RobolectricTest {
}
記住要import Powermock版本的mockito api,不然會出現稀奇古怪的bug。
比如
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;
有時候Robolectric會提示你不能找到 Manifest.xml ,這時候一般clean project就可以了。
 
Robolectric 3.0 暫時不支持加載jniLibs,如果你的代碼用到了jniLibs,就只能使用 Android Instrumentation Tests了,如果你像我一樣  extends android.app.Application 來創建自己的Application類,並在該Application類中寫了了需要調用jniLibs的代碼,可以使用以下的方法在unit test中跳過這些代碼。
 
@Override
public void onCreate() {
    super.onCreate();
    if (isJUnitTest()) {
        // 省略掉包含jniLibs的library的初始化
    } else {
        // 進行正常的初始化
    }
}

public static boolean isJUnitTest() {
    StackTraceElement[] stackTrace = new Throwable().getStackTrace();
    for (StackTraceElement element : stackTrace) {
        if (element.getClassName().startsWith("org.junit.")) {
            return true;
        }
    }
    return false;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM