Help us understand the problem. What is going on with this article?

targetSdkVersion を 29 に上げても Robolectric のテストを動くようにする

概要

Java 8 の環境で targetSdkVersion を 29 に上げたら RobolectricTestRunner を使うユニットテストが動かなくなったので、対応方法を調べました。

問題

テストを実行すると、以下の例外が出てテストが失敗します。

java.lang.IllegalArgumentException: failed to configure jp.toastkid.yobidashi.media.image.preview.RotateMatrixFactoryTest.test: Package targetSdkVersion=29 > maxSdkVersion=28
    at org.robolectric.RobolectricTestRunner.getChildren(RobolectricTestRunner.java:240)
    at org.junit.runners.ParentRunner.getFilteredChildren(ParentRunner.java:426)

// 中略

    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalArgumentException: Package targetSdkVersion=29 > maxSdkVersion=28
    at org.robolectric.plugins.DefaultSdkPicker.configuredSdks(DefaultSdkPicker.java:118)
    at org.robolectric.plugins.DefaultSdkPicker.selectSdks(DefaultSdkPicker.java:69)
    at org.robolectric.RobolectricTestRunner.getChildren(RobolectricTestRunner.java:206)

対応

現時点の最新バージョンの 4.3.1 を使えば SDK 29に対応はしているようですが、Java 9 以上が必要です。

java.lang.UnsupportedOperationException: Failed to create a Robolectric sandbox: Android SDK 29 requires Java 9 (have Java 8)

    at org.robolectric.RobolectricTestRunner.getSandbox(RobolectricTestRunner.java:265)
    at org.robolectric.RobolectricTestRunner.getSandbox(RobolectricTestRunner.java:63)
    at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:215)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

Workaround

諸事情で Java 8 を使わざるを得ない場合は、 src/test/resources/robolectric.properties というファイルを置き、以下の設定を入れることで動くようになりました。Java 9 を導入するまではこれで対応しましょう。

robolectric.properties
sdk=28

今後、sdk 28を指定していたことでテストに不具合が起こる可能性も否定はできないので、早めに Java と Robolectric をアップグレードする方が良さそうです。

参考

toastkidjp
Web 系企業の Android アプリ開発者です。
https://github.com/toastkidjp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした