View Javadoc
1   /**************************************************************************
2    *
3    * Copyright (c) 2018-2019 Yawg project contributors.
4    *
5    **************************************************************************/
6   
7   package com.varmateo.testutils;
8   
9   import org.junit.rules.TestRule;
10  import org.junit.runner.Description;
11  import org.junit.runners.model.Statement;
12  
13  
14  /**
15   *
16   */
17  public final class LogStartAndEndRule implements TestRule {
18  
19      private static final String MSG_START = "%n>>>>>> START - %s <<<<<<";
20      private static final String MSG_END = ">>>>>> END - %s (%.3f ms) <<<<<<";
21  
22      /**
23       *
24       */
25      @Override
26      public Statement apply(
27              final Statement base,
28              final Description description) {
29  
30          return new Statement() {
31              @Override
32              public void evaluate()
33                      throws Throwable {
34                  runTest(base, description);
35              }
36          };
37      }
38  
39  
40      private void runTest(
41              final Statement base,
42              final Description description)
43              throws Throwable {
44  
45          long startTime = System.nanoTime();
46          String testName = description.getMethodName();
47          Throwable error = null;
48  
49          String startMsg = String.format(MSG_START, testName);
50  
51          System.out.println(startMsg);
52  
53          try {
54              base.evaluate();
55          } catch ( Throwable e ) {
56              error = e;
57          }
58  
59          long durationNanos = System.nanoTime() - startTime;
60          double durationMillis = durationNanos / 1_000_000.0;
61          String endMsg = String.format(MSG_END, testName, durationMillis);
62  
63          System.out.println(endMsg);
64  
65          if ( error != null ) {
66              throw error;
67          }
68      }
69  
70  }