美文网首页
Robolectric

Robolectric

作者: Andrew玩Android | 来源:发表于2017-09-18 02:07 被阅读449次

开始单元测试之前还是要先了解TDD

中文版:TDD 已死?让我们再聊聊 TDD

英文版:Introduction to Test Driven Development (TDD)


Robolectric概述

Android的单元测试可以分为两部分:

Local unit tests:运行于本地JVM
Instrumented test:运行于真机或者模拟器

如果使用Local测试,需要保证测试过程中不会调用Android系统API,否则会抛出RuntimeException异常。
因为Local测试是直接跑在本机JVM的,而之所以我们能使用Android系统API,是因为编译的时候,我们依赖了一个名为“android.jar”的jar包,但是jar包里所有方法都是直接抛出了一个RuntimeException,是没有任何任何实现的,这只是Android为了我们能通过编译提供的一个Stub!

当APP运行在真实的Android系统的时候,由于类加载机制,会加载位于framework的具有真正实现的类。由于我们的Local是直接在PC上运行的,所以调用这些系统API便会出错。

那么问题来了,我们既要使用Local测试,但测试过程又难免遇到调用系统API那怎么办?其中一个方法就是mock objects,比如借助Mockito,另外一种方式就是使用Robolectric

Robolectric就是为解决这个问题而生的。它实现一套JVM能运行的Android代码,然后在unit test运行的时候去截取android相关的代码调用,然后转到他们的他们实现的Shadow代码去执行这个调用的过程。


根据官网教程配置使用即可


本文配置环境:

Android Studio 3.0 Beta 5
Gradle Warpper: gradle-4.1-all
Gradle 插件:gradle:3.0.0-beta5
Android SDK:25
Robolectric:3.4.2

配置过程异常:

1.1 unknown property 'includeAndroidResources:

testCompile "org.robolectric:robolectric:3.4.2"

android {
  testOptions {
    unitTests {
      includeAndroidResources = true
    }
  }
} 

==注意==

  • 若写成testCompile,则测试代码放在 test 文件夹中
  • 若写成androidTest,则测试代码放在 androidTest 文件夹中

按照官网如上配置后 报错,Gradle Sync Error:

Error:(22, 0) Could not set unknown property 'includeAndroidResources' for object of type com.android.build.gradle.internal.dsl.TestOptions$UnitTestOptions.
<a href="openFile:G:\android\Samples\Tests\robolectric\app\build.gradle">Open File</a>

未知的属性includeAndroidResources,gradle版本由3.0.0-alpha8修改至3.0.0-beta5解决问题。

参考自: 'includeAndroidResources' is not working in AS3.0 Beta 2

1.2 Cannot Resolve symbol RobolectricTestRunner

@RunWith(RobolectricTestRunner.class)
public class SandwichTest {
}

尝试写一个 Robolectric Test的时候提示:cannot resolve robolectrictestrunner
参考robolectric github例子,将gradle版本修改为3.0.0-beta3,下载失败时添加maven { url 'https://maven.google.com' }

完整配置,Project build.gradle:

repositories {
        maven {
            url 'https://maven.google.com'
        }
        jcenter()
    }

1.2.1

如果依然存在 Cannot Resolve symbol RobolectricTestRunner,并且测试类在src/androidTest 目录下,移至src/test目录下,参考自: cannot resolve symbol RobolectricTestRunner

1.3 java.lang.NullPointerException at sun.nio.fs.WindowsPathParser.parse

Error:Cause: java.lang.NullPointerException 
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:98)

Clear Project --> Gradle sync后解决

参考自:gradle-error-upgrading-to-android-studio-3-0-beta-1

1.4 Cannot resolve method 'assertThat(android.content.Intent)

参考官方例子时,遇到Cannot resolve method 'assertThat(android.content.Intent)的问题,该assertThat不是junithamcrest库方法,而是Android AssertJAssertJ库,引入库即可。

testCompile 'org.assertj:assertj-core:1.7.1'

参考自:importing correct AssertThat method for Robolectric Test

1.5 java.lang.AssertionError: Expecting: <"Intent { cmp=*** } (Intent@4e96cb04)"> to be equal to: <"Intent { cmp=*** } (Intent@70ecf57b)"> but was not.

    @Test
    public void clickingLogin_shouldStartLoginActivity() {
        WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
        activity.findViewById(R.id.login).performClick();

        Intent expectedIntent = new Intent(activity, LoginActivity.class);
        AbstractObjectAssert<?, Intent> actual = assertThat(shadowOf(activity).getNextStartedActivity());
        actual.isEqualTo(expectedIntent);
    }

运行官网的例子时,test failed:

java.lang.AssertionError: 
Expecting:
 <"Intent { cmp=robolectirc.example.andrew.robolectric/.LoginActivity } (Intent@4e96cb04)">
to be equal to:
 <"Intent { cmp=robolectirc.example.andrew.robolectric/.LoginActivity } (Intent@70ecf57b)">
but was not.

很明显两个Intent值相同但是对象引用不同导致的异常。 已经提了Issue 等待回复。

改为使用Junit的assertEquals后测试通过:

    @Test
    public void clickingLogin_shouldStartLoginActivity() {
        WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
        activity.findViewById(R.id.login).performClick();

        // 期望意图
        Intent expectedIntent = new Intent(activity, LoginActivity.class);

        // 获取跳转的意图
        Intent actual = ShadowApplication.getInstance().getNextStartedActivity();

        // 假设一致
        assertEquals(expectedIntent.getComponent(), actual.getComponent());
    }

奇怪的是,robolectric github例子按照README.md,使用命令行gradlew test可以成功测试,但在IDEA中运行DeckardActivityTestRun Test却报错:

!!! JUnit version 3.8 or later expected: 

java.lang.RuntimeException: Stub!
    at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
    at junit.textui.TestRunner.<init>(TestRunner.java:54)

DeckardEspressoTest 运行并且测试通过。


参考:

Android单元测试之Robolectric框架

用Robolectric来做Android unit testing

Android robolectric 入门

Robolectric使用教程

Android单元测试框架Robolectric3.0介绍(一)

importing correct AssertThat method for Robolectric Test

assertj-android

相关文章

网友评论

      本文标题:Robolectric

      本文链接:https://www.haomeiwen.com/subject/zcqysxtx.html