0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Kotlin】JUnit5でJUnit4のRuleを使う方法

Posted at

2020年1月現在、JUnit4からJUnit5への過渡期の中でその両者が混合しているようなソースコードはそれなりにあるかと思います。
もしくは今後リファクタリングの際に4から5へアップグレードする必要があるかもしれません。

しっかりお金がもらえて時間があるなら一から作り直すのもありですが、世の中そんなに上手くいくことの方が少ないです。
なので今回はJUnit5で廃止されてしまった@Ruleを場当たり的に応急処置としてとりあえず対応するための方法をご紹介します。

その前に

JUnit5のドキュメントには「今後JUnit5で新しい拡張機能を開発する場合は、JUnit4の@Ruleではなく、JUnit JupiterのExtension Modelを使ってね。」と書いてあります。

However, if you intend to develop a new extension for JUnit 5 please use the new extension model of JUnit Jupiter instead of the rule-based model of JUnit 4.

なので間違ってもこれから記載する方法でJUnit4の@Ruleをずっと使い続けて良いわけではないので、その点は注意してください。

方法

まずはjuint-jupiter-migrationsupportを入れます。

testImplementation("org.junit.jupiter:junit-jupiter-migrationsupport:5.5.2")

そうしたら@Ruleを使用しているクラスに@EnableRuleMigrationSupportアノテーションを付けます。

@EnableRuleMigrationSupport
class OldJunit4Tests {
    
    @get:Rule
    val tempDir = TemporaryFolder()
    
    @Test
    fun `TemporaryFolderを使うテスト`() {
        // doSomeThing
    }
}    

以上です。

TemporaryFolderぐらいだったら@TempDirが追加されたのでそちらを使用すれば良いのですが、プロジェクトの都合上Ruleを大量に定義していた場合などはこの方法で乗り切ると良いでしょう。

おまけ

JUnit5では@Ignoreがなくなり、代わりにそれと似た機能を持つ@Disabledが使用されるようになりました。
そちらも似たような方法で対処が可能です。

@Ruleの時と同様にjuint-jupiter-migrationsupportを入れ、@ExtendWith(IgnoreCondition.class)または@EnableJUnit4MigrationSupportを使用します。

// @ExtendWith(IgnoreCondition.class)
@EnableJUnit4MigrationSupport
class OldJunit4Tests {
    
    @get:Ignore
    @Test
    fun `testWillBeIgnored`() {
        // doSomeThing
    }
}    
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?