How does Junit @Rule work?

2019-01-07 03:11发布

I want to write test cases for a bulk of code, I would like to know details of JUnit @Rule annotation feature, so that I can use it for writing test cases. Please provide some good answers or links, which give detailed description of its functionality through a simple example.

4条回答
爷、活的狠高调
2楼-- · 2019-01-07 03:24

I found this article explains @Rules rather well, especially check out the last section "The Sequence Of Events In Detail"

查看更多
戒情不戒烟
3楼-- · 2019-01-07 03:25

Junit Rules work on the principle of AOP (aspect oriented programming). It intercepts the test method thus providing an opportunity to do some stuff before or after the execution of a particular test method.

Take the example of the below code:

public class JunitRuleTest {

  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void testRule() throws IOException {
    File newFolder = tempFolder.newFolder("Temp Folder");
    assertTrue(newFolder.exists());
  }
} 

Every time the above test method is executed, a temporary folder is created and it gets deleted after the execution of the method. This is an example of an out-of-box rule provided by Junit.

Similar behaviour can also be achieved by creating our own rules. Junit provides the TestRule interface, which can be implemented to create our own Junit Rule.

Here is a useful link for reference:

查看更多
何必那么认真
4楼-- · 2019-01-07 03:30

Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way.

For instance, ExternalResource executes code before and after a test method, without having to use @Before and @After. Using an ExternalResource rather than @Before and @After gives opportunities for better code reuse; the same rule can be used from two different test classes.

The design was based upon: Interceptors in JUnit

For more information see JUnit wiki : Rules.

查看更多
疯言疯语
5楼-- · 2019-01-07 03:35

tl;dr for how it works: JUnit wraps your test method in a Statement object so statement.Execute() runs your test. Then instead of calling statement.Execute() directly to run your test, JUnit passes the Statement to a TestRule with the @Rule annotation. The TestRule's "apply" function returns a new Statement given the Statement with your test. The new Statement's Execute() method can call the test Statement's execute method (or not, or call it multiple times), and do whatever it wants before and after. Now JUnit has a new Statement that does more than just run the test, and it can again pass that to any more rules before finally calling Execute.

查看更多
登录 后发表回答