What is the best practice to determine the execution time of the business relevant code of my junit?

前端 未结 3 1864
心在旅途
心在旅途 2020-12-08 08:05

The test execution time which is displayed in eclipse->junit-view depends on the whole test case execution which includes:

  • Testdata preperation
  • Execut
3条回答
  •  无人及你
    2020-12-08 08:55

    JUnit 4.12 introduced the Stopwatch @Rule. It is quite straigthforward to use and should become the de facto way of verifying time spent during tests. Here's a sample class showcasing its functionalities:

    public static class StopwatchTest {
         private static final Logger logger = Logger.getLogger("");
    
         private static void logInfo(Description description, String status, long nanos) {
             String testName = description.getMethodName();
             logger.info(String.format("Test %s %s, spent %d microseconds",
                                       testName, status, TimeUnit.NANOSECONDS.toMicros(nanos)));
         }
    
         @Rule
         public Stopwatch stopwatch = new Stopwatch() {
             @Override
             protected void succeeded(long nanos, Description description) {
                 logInfo(description, "succeeded", nanos);
             }
    
             @Override
             protected void failed(long nanos, Throwable e, Description description) {
                 logInfo(description, "failed", nanos);
             }
    
             @Override
             protected void skipped(long nanos, AssumptionViolatedException e, Description description) {
                 logInfo(description, "skipped", nanos);
             }
    
             @Override
             protected void finished(long nanos, Description description) {
                 logInfo(description, "finished", nanos);
             }
         };
    
         @Test
         public void succeeds() {
         }
    
         @Test
         public void fails() {
             fail();
         }
    
         @Test
         public void skips() {
             assumeTrue(false);
         }
    
         @Test
         public void performanceTest() throws InterruptedException {
             // An example to assert runtime:
             long delta = 30;
             Thread.sleep(300L);
             assertEquals(300d, stopwatch.runtime(MILLISECONDS), delta);
             Thread.sleep(500L);
             assertEquals(800d, stopwatch.runtime(MILLISECONDS), delta);
         }
    }
    

提交回复
热议问题