What does @Rule do?

When I tried to create a temporary file for unit tests, I came across this answer that mentioned "TemporaryFolder JUnit @Rule" and a link explaining how to use it. It looks like this:

@Rule
public TemporaryFolder testFolder = new TemporaryFolder();

and then testFolder.newFile("file.txt")

My question is what the @Rule annotation does?

Removing annotation does not change anything.

+4
source share
1 answer

Like the documentation Ruleand TemporaryFolder, he takes care of creating a temporary directory before each test method of the corresponding class and deleting this temporary folder (and its contents) after each test method.

, TestRule MethodRule , ExternalResource.

@Before @After . . , , , . , , , , .

, , (Jetty Tomcat), @Rule, .

, @Rule @ClassRule public static. .

@ClassRule
public static JettyServerRule server = new JettyServerRule(new EmbeddedJetty());

@Test
public void myUnitTest() {
    RestTemplate restTemplate = new RestTemplate();
    String url = String.format("http://localhost:%s", server.getPort());

    String response = restTemplate.getForObject(url, String.class);

    assertEquals("Hello World", response);
}

Jetty , .

RuleChain:

@Rule
public RuleChain chain= RuleChain.outerRule(new LoggingRule("outer rule")
                                 .around(new LoggingRule("middle rule")
                                 .around(new LoggingRule("inner rule");

, JAX-RS, Restlet on Jetty, :

public static SpringContextRule springContextRule;
public static RestletServerRule restletServer;

static {
    springContextRule = new SpringContextRule(JaxRsRestletTestSpringConfig.class);
    restletServer = new RestletServerRule(springContextRule.getSpringContext());
}

@ClassRule
public static RuleChain ruleChain = RuleChain.outerRule(restletServer).around(springContextRule);

// Tempus Fugit rules
@Rule
public ConcurrentRule concurrently = new ConcurrentRule();

@Rule
public RepeatingRule repeatedly = new RepeatingRule();

spring Restlet/Jetty spring bean . , Tempus Fugit , , concurrency .

+5

Source: https://habr.com/ru/post/1599184/


All Articles