Junit Deepdive Part3 Followup Quiz

Follow up

As a small follow up on rules i want to provide two usecases which i am using quite often in my projects:

  1. JPA/JAXRS Rules:
    In almost every of my projects where i typically work more as a backend java engineer i have to deal with JPA/Hibernate or JAXRS endpoints and therefore have to write tests for those services. And with that i mean more simple DAO or endpoint tests otherwise i use Arquillian but that is another topic. In order to not reinventing the wheel i use the rules from Adam Bien which can be found here.

  2. Overcome JUnit restrictions of runners
    The current release of JUnit (version 4.12) has the restriction that a test class can only have one runner. Therefore it is not possible to combine functionalities of multiple runners which in some case can really be useful. But with the concept of rules it is possible if the functionality of one runner is extracted into a rule. Fortunately for us there are plenty of rules available already. Here are two typical problems:

Quiz

This short review quiz is related to the previous article DeepDive Part3 Rules.

A. Which of the following choices do you have to apply to get non class rules running?

  1. add annotation @Rule
  2. make rule member public
  3. add @RunWith(RuleRunner.class)
  4. initialize member

B. Which of the following statements are true?

  1. @Before/@After lifecycle hooks are always execute before rules.
  2. @Before/@After lifecycle hooks are always execute after rules.

C. What happens in the following code snippet?

 1 public class RuleTest {
 2     @Rule public LoggingRule rule = new LoggingRule();
 3 
 4     @Test public void test() {
 5         System.out.println("test");
 6     }
 7 
 8     @AfterClass public static void afterClass() {
 9         System.out.println("afterclass");
10     }
11 }
12 
13 class LoggingRule implements TestRule {
14     @Override
15     public Statement apply(Statement base, Description description) {
16         return new Statement() {
17             @Override
18             public void evaluate() throws Throwable {
19                 System.out.println("LoggingRule");
20                 base.evaluate();
21             }
22         };
23     }
24 }
  1. Prints LoggingRule, test, afterclass.
  2. Prints test, afterclass.
  3. throws NullPointerException.

D. Okay, the previous one was easy. What happens if you change line 2 into

1 @Rule public LoggingRule rule;
  1. Prints LoggingRule, test, afterclass.
  2. Prints test, afterclass.
  3. throws NullPointerException.

The solutions can be found here in white color: A124; B2; C1; D2