JUnit 4 rules

Due to the strict limitation of uniqueness of a JUnit 4 runner within the same test class, version 4.7 of JUnit introduced the concept of method-level rules, which are annotated fields in a test class with @Rule. These rules allow for addition or redefinition of test behavior by executing some code before and after the execution of the test. JUnit 4.9 also incorporates the concept of class-level rules, which are rules that are executed before and after all tests within the class. These rules are identified by annotating static fields with @ClassRule, as shown in the following example:

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class MyRuleTest {

@ClassRule
public static TemporaryFolder temporaryFolder = new TemporaryFolder();

@Test
public void anotherTest() {
// my test code
}

}

While rules are simpler and mostly compostable, they have other drawbacks. The main inconvenience when using JUnit 4 rules for complex tests is that we are not able to use a single rule entity for method-level and class-level. At the end of the day, this imposes limitations to customize the life cycle management (the before/after behavior).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.14.132