Junit @Rule與@ClassRule註解

@Before/@After Vs @Rule

若是咱們想再多個測試類中服用編寫的@Before裝飾的setUp()方法和@After裝飾的tearDown()方法時,能夠考慮使用@Rule註解。
在使用@Rule註解時,@Rule修飾的類須要實現TestRuleMethodRule(計劃被@TestRule所取代)接口中的apply方法。app

@Rule Vs @ClassRule

@ClassRule對標@BeforeClass/@AfterClass
@Rule對標@Before/@After
@ClassRule 是 static方法,@Rule不是。但@ClassRule@Rule修飾的成員變量都必須爲publicide

TestRule 示例:

public class TestMethodNameLogger implements TestRule {
 
    private static final Logger LOG = LoggerFactory.getLogger(TestMethodNameLogger.class);
 
    @Override
    public Statement apply(Statement base, Description description) {
        logInfo("Before test", description);
        try {
            return new Statement() {
                @Override
                public void evaluate() throws Throwable {
                    base.evaluate();
                }
            };
        } finally {
            logInfo("After test", description);
        }
    }
 
    private void logInfo(String msg, Description description) {
        LOG.info(msg + description.getMethodName());
    }
}

當咱們在實現apply方法時,咱們必須返回一個Statement的實例。這個實例表明着咱們在Junit運行時中的測試。在調用evaluate()方法時測試被執行。 測試

Junit的Rule可能會以任意順序執行。若是想要控制多個Rule的執行順序,可使用@RuleChainlua

參考資料:

相關文章
相關標籤/搜索