1package org.junit; 2 3import java.lang.annotation.ElementType; 4import java.lang.annotation.Retention; 5import java.lang.annotation.RetentionPolicy; 6import java.lang.annotation.Target; 7 8/** 9 * Annotates fields that reference rules or methods that return a rule. A field must be public, not 10 * static, and a subtype of {@link org.junit.rules.TestRule} (preferred) or 11 * {@link org.junit.rules.MethodRule}. A method must be public, not static, 12 * and must return a subtype of {@link org.junit.rules.TestRule} (preferred) or 13 * {@link org.junit.rules.MethodRule}. 14 * <p> 15 * The {@link org.junit.runners.model.Statement} passed 16 * to the {@link org.junit.rules.TestRule} will run any {@link Before} methods, 17 * then the {@link Test} method, and finally any {@link After} methods, 18 * throwing an exception if any of these fail. If there are multiple 19 * annotated {@link Rule}s on a class, they will be applied in order of fields first, then methods. 20 * However, if there are multiple fields (or methods) they will be applied in an order 21 * that depends on your JVM's implementation of the reflection API, which is 22 * undefined, in general. Rules defined by fields will always be applied 23 * before Rules defined by methods. You can use a {@link org.junit.rules.RuleChain} if you want 24 * to have control over the order in which the Rules are applied. 25 * <p> 26 * For example, here is a test class that creates a temporary folder before 27 * each test method, and deletes it after each: 28 * <pre> 29 * public static class HasTempFolder { 30 * @Rule 31 * public TemporaryFolder folder= new TemporaryFolder(); 32 * 33 * @Test 34 * public void testUsingTempFolder() throws IOException { 35 * File createdFile= folder.newFile("myfile.txt"); 36 * File createdFolder= folder.newFolder("subfolder"); 37 * // ... 38 * } 39 * } 40 * </pre> 41 * <p> 42 * And the same using a method. 43 * <pre> 44 * public static class HasTempFolder { 45 * private TemporaryFolder folder= new TemporaryFolder(); 46 * 47 * @Rule 48 * public TemporaryFolder getFolder() { 49 * return folder; 50 * } 51 * 52 * @Test 53 * public void testUsingTempFolder() throws IOException { 54 * File createdFile= folder.newFile("myfile.txt"); 55 * File createdFolder= folder.newFolder("subfolder"); 56 * // ... 57 * } 58 * } 59 * </pre> 60 * <p> 61 * For more information and more examples, see 62 * {@link org.junit.rules.TestRule}. 63 * 64 * @since 4.7 65 */ 66@Retention(RetentionPolicy.RUNTIME) 67@Target({ElementType.FIELD, ElementType.METHOD}) 68public @interface Rule { 69 70}