【问题标题】:Android UnitTest - RuntimeExceptions for Android classesAndroid 单元测试 - Android 类的运行时异常
【发布时间】: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


【解决方案1】:

当您使用 PowerMockRunner 跑步时,您实际上并没有通过 robolectric 跑步。通常,当您需要 robolectric 框架时,您会这样运行:

@RunWith(RobolectricTestRunner.class)

【讨论】:

  • 我尝试使用 RobolectricTestRunner,但后来我得到了 PowerMock 功能的 UnsupportedOperationException。如何配置我的 TestCase 类以使用 RobolectricTestRunner 并且仍然能够同时使用 Mockito 和 PowerMock?
  • Mockito 开箱即用,PowerMock 给您带来了麻烦。关于如何设置它有一些 SO 答案,您可以查看它们是否有助于解决您遇到的问题。例如stackoverflow.com/questions/20557769/…
猜你喜欢
  • 1970-01-01
  • 2011-03-22
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多