Robolectric没有为具有不同应用ID的风味找到资源

时间:2018-02-19 11:57:48

标签: android unit-testing android-testing robolectric

在Android Studio中,我正在使用Robolectric编写多种版本的单元测试,似乎我只能使用默认的应用程序ID访问flavor的测试中的资源。

我的测试目录结构是:

-src
  ...
  - test (these tests will run on all flavors)
      - java
          - com.example.main
              - UnitTest.java
  - testDefault (these tests will only run on flavor "main")
      - java
          - com.example.main
              - DefaultUnitTest.java
  - testOtherFlavor (these tests will only run on flavor "otherFlavor")
      - java
          - com.example.otherflavor
              - OtherFlavorUnitTest.java
  - main
    ...
    - res
      - values
        - strings.xml
  - otherflavor
    - res
      - values
        - strings.xml

在我的build.gradle中,我有

productFlavors {
  default{}
  otherFlavor {
    applicationId "com.example.otherflavor"
    versionNameSuffix "-otherFlavor"
  }
}

我的测试如下:

package com.example.otherflavor;

import android.context.Context;
import com.example.main.R;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;

@RunWith(RobolectricTestRunner.class)
@Config(packageName = com.example.otherflavor)
public class OtherFlavorUnitTest {

    private Context contextMock;

    @Test
    public void test() {

        contextMock = RuntimeEnvironment.application.getApplicationContext();

        System.out.println(contextMock.getString(R.string.someString));

    }

}

someString位于两个具有不同值的strings.xml文件中,因此在运行flavor“otherflavor”时,其strings.xml的值将覆盖默认flavor的值。问题是,当我在DefaultUnitTest.java中运行此代码(相应地更改了包名称)时,测试通过,但是当我在OtherFlavorUnitTest.java中运行此代码时,我得到:

android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f0e0059 in packages [com.example.otherflavor, android]

然而如果我从build.gradle中删除“applicationId "com.example.otherflavor"”,则测试会通过(并且getString()检索的资源确实是otherFlavor的资源,而不是默认风格)

有人知道为什么当风味具有不同的应用ID时,Robolectric无法找到资源吗?

2 个答案:

答案 0 :(得分:0)

简短的回答是test必须足够灵活,无论applicationId设置为何,都必须运行其测试。正确完成后,从Build Variant窗口中选择flavor。然后测试针对当前选择的风味运行。或者,您可以从命令行运行./gradlew testFlavor./gradlew testDefault

答案 1 :(得分:0)

您可以在每个风味测试目录中创建一个类作为资源的提供者,这样每个文件都会有一个与 aplicationId 匹配的导入,如 com.example.myapp.flavorOne.test.R 或 flavorTwo.test.R 然后从将在 androidTest(主测试目录)上的测试类中,您可以从您创建的与您所在的构建变体(风格)相匹配的资源提供程序中获取资源