【发布时间】:2015-01-26 10:43:38
【问题描述】:
我正在开发一个 SDK,我正在尝试对其执行 UnitTests。 这意味着我的大部分项目都是纯 java 代码,在某些地方涉及 Android 代码。 我想在我的 SDK 上执行 UnitTest,我决定使用 Roboelectric、Mockito 和 PowerMock(用于静态方法模拟)。
除了一个问题外,一切正常: 当我的测试调用任何包含 Android 类的方法时,我的测试会崩溃(由于 Stub 问题)。 我知道我无法测试 Activity、Views 和更多类,但问题是即使我的函数包含对 Log 类的使用,我也会得到 RuntimeException。
我该如何处理这个问题? 我决定使用纯 UnitTest,因为我的大部分代码不包含除 Log 类之外的 Android 类。通过使用纯 java UnitTest,我不需要任何设备来运行,因此我可以同时执行多个测试任务。
我尝试在我的 gradle 中包含 android.jar 文件,但没有成功。
我该怎么办? 1.坚持纯Java UnitTest:那么我怎么能忽略/导入日志指令。 2. 迁移到 Android 测试框架:什么最适合我的需求?
这是我的 gradle 文件中与测试相关的部分:
robolectric {
// configure the set of classes for JUnit tests
include '**/*UnitTest.class'
// confgure max heap size of the test JVM
maxHeapSize = '2048m'
// configure the test JVM arguments
jvmArgs '-XX:MaxPermSize=512m', '-XX:-UseSplitVerifier'
// configure whether failing tests should fail the build
ignoreFailures true
// use afterTest to listen to the test execution results
afterTest { descriptor, result ->
println "Executing test for {$descriptor.name} with result: ${result.resultType}"
}
}
dependencies {
androidTestCompile 'org.robolectric:robolectric:2.3'
androidTestCompile 'junit:junit:4.10'
androidTestCompile 'org.mockito:mockito-core:1.8.5'
androidTestCompile 'org.powermock:powermock-mockito-release-full:1.4.9'
androidTestCompile files('../libs-test/json.jar')
}
这是一个 TestCase 类的示例:
import android.util.Log;
import junit.framework.TestCase;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.Test;
import org.json.JSONObject;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticInClass.class)
public class ClassExampleUnitTest extends TestCase{
@Test
public void testSimple(){
Log.d("UnitTest", "test");
assertTrue(true);
}
}
【问题讨论】:
-
在 gradle 文件中提及
robolectric是不够的。您还需要使用RobolectricTestRunner,这将需要使用PowerMock规则而不是PowerMockRunner。但是你需要PowerMockRunner吗?从您的示例课程中,您没有 -
@EugenMartynov 我使用 PowerMock 来模拟静态方法
标签: java android unit-testing robolectric