如何使用@Rule在JUnit中获得测试时间?

时间:2019-10-22 17:06:00

标签: java junit junit4 junit5

我有一个使用JUnit编写的测试类,并且需要使用@Rule注释记录每次测试的时间。 我该怎么做? 我需要使用StopWatch()吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下示例:

Source

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Stopwatch;
import org.junit.runner.Description;

import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;

public class StopwatchTest {

     private static final Logger logger = Logger.getLogger(StopwatchTest.class.getSimpleName());

     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 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 {
        long delta = 30;
        Thread.sleep(300L);
        assertEquals(300d, stopwatch.runtime(MILLISECONDS), delta);
        Thread.sleep(500L);
        assertEquals(800d, stopwatch.runtime(MILLISECONDS), delta);
    }
 }