LoginSignup
6
7

More than 5 years have passed since last update.

JUnitでRuleChainを使う

Posted at

テストコードを書いていると、例外を検証するケースや、テストメソッドを実行する度に一時ディレクトリを作成して終了時には自動的に削除する、といったようなケースがあると思う。
この手のテストはJUnitのRuleを利用することで、少ないコード量でシンプルに書くことが出来る。例えば例外を検証する場合はExpectedException、一時ディレクトリやファイルを作成するような場合はTemporaryFolderを利用する。
JUnitのTemporaryFolderルールのディレクトリやファイルの出力先

HogeTest.java
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();

@Rule
public ExpectedException thrown = ExpectedException.none();

ただ、上記のようにRuleを複数適用させようとすると、Ruleが実行される順序の制御はJavaVMのリフレクションAPIの実装に依存してしまい、開発者が期待するようなテストの実施が困難になってくる。

そこで使うのがRuleChain

そういった際に利用するのがJUnit4.10から導入されたRuleChain。
以下のような感じで、利用するRuleを定義してRuleChainのouterRule、aroundの引数に適用したい順に指定する。

HogeTest.java

public TemporaryFolder temporaryFolder = new TemporaryFolder();
public ExpectedException thrown = ExpectedException.none();

@Rule
public RuleChain ruleChain = RuleChain.outerRule(this.temporaryFolder).around(this.thrown);

こうすることで、指定した順序(上記の場合、TemporaryFolder→ExpectedException)でRuleが呼ばれるようになる。また、3つ以上Ruleを適用したい場合は、

HogeTest.java

public TemporaryFolder temporaryFolder = new TemporaryFolder();
public ExpectedException thrown = ExpectedException.none();
public ErrorCollector errorCollector = new ErrorCollector();

@Rule
public RuleChain ruleChain = RuleChain.outerRule(this.temporaryFolder).around(this.thrown).around(this.errorCollector);

のように.aroundでつなげていけばOK。

6
7
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
6
7