Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The JUnit way to compose reusable code (instead of inheriting from it) are Rules.</p> <p>See <a href="https://github.com/junit-team/junit/wiki/Rules" rel="noreferrer">https://github.com/junit-team/junit/wiki/Rules</a></p> <p>Here is a dumb sample, but you'll get the point.</p> <pre><code>import org.junit.rules.TestRule; import org.junit.runners.model.Statement; import org.junit.runner.Description; public class MyTestRule implements TestRule { @Override public Statement apply(final Statement statement, Description description) { return new Statement() { public void evaluate() throws Throwable { // Here is BEFORE_CODE try { statement.evaluate(); } finally { // Here is AFTER_CODE } } }; } } </code></pre> <p>You can then use your TestRule like this:</p> <pre><code>import org.junit.Rule; public class MyTest { @Rule public MyTestRule myRule = new MyTestRule(); } </code></pre> <p>BEFORE_CODE and AFTER_CODE will then be executed around each of your test methods.</p> <p>If you need to run your code only once per class, use your TestRule as a @ClassRule:</p> <pre><code>import org.junit.ClassRule; public class MyTest { @ClassRule public static MyTestRule myRule = new MyTestRule(); } </code></pre> <p>Now, <code>BEFORE_CODE</code> and <code>AFTER_CODE</code> will be executed around each of your test class.</p> <p><a href="http://junit.org/javadoc/latest/org/junit/Rule.html" rel="noreferrer">@Rule</a> field is not static, <a href="http://junit.org/javadoc/latest/org/junit/ClassRule.html" rel="noreferrer">@ClassRule</a> field is.</p> <p>A @ClassRule can be declared in a Suite too.</p> <p>Note that you can declare several rules in a single test class, that's how you compose test lifecycles at test-suites, test-classes and test-methods levels.</p> <p>A Rule is an object that you instanciate in your test classes (statically or not). You can add contructor parameters if needed.</p> <p>HTH</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload