他の応答で述べたように、JUnitのメソッドの検索順序は保証されていないため、@Before
メソッドの実行順序は保証できません。同じことが@Rule
の場合も同じですが、保証の欠如があります。これが常に同じコードである場合、2つのメソッドに分割する点はありません。
2つの方法があり、もっと重要なことに、複数の場所から使用する場合は、4.10で導入されたRuleChainを使用してルールを組み合わせることができます。これは以下のような、ルールの特定の順序付けを可能にする:
public static class UseRuleChain {
@Rule
public TestRule chain= RuleChain
.outerRule(new LoggingRule("outer rule"))
.around(new LoggingRule("middle rule"))
.around(new LoggingRule("inner rule"));
@Test
public void example() {
assertTrue(true);
}
}
これが生成します。
starting outer rule
starting middle rule
starting inner rule
finished inner rule
finished middle rule
finished outer rule
をですから、4.10にアップグレードするか、または単にクラスを盗みます。
あなたのケースでは、クライアントセットアップ用とオブジェクト用の2つのルールを定義し、それらをRuleChain
で組み合わせることができます。 ExternalResourceを使用してください。
public static class UsesExternalResource {
private TestRule clientRule = new ExternalResource() {
@Override
protected void before() throws Throwable {
setupClientCode();
};
@Override
protected void after() {
tearDownClientCode()
};
};
@Rule public TestRule chain = RuleChain
.outerRule(clientRule)
.around(objectRule);
}
だから、あなたは、次の実行順序があるでしょう:
clientRule.before()
objectRule.before()
the test
objectRule.after()
clientRule.after()
何基底クラスはどうですか?そうでなければ、メソッドに対して何の問題も見ません... – wuppi