Record time it takes JUnit tests to run

后端 未结 7 1422
无人共我
无人共我 2021-02-04 11:52

I would like to record how long it takes my JUnit test to run programmatically. I have a large number of tests in various test classes, and I would like to find out how long ea

7条回答
  •  甜味超标
    2021-02-04 12:48

    Create your own TestWatcher implementation which catches every test method running. Using Guava Stopwatch you can measure time for each test:

    public class TimeTestWatcher extends TestWatcher {
        private Stopwatch stopwatch = Stopwatch.createUnstarted();
    
        protected void starting(Description description) {
            stopwatch.start();
        }
    
        protected void finished(Description description) {
            stopwatch.stop();
    
            String testName = description.getMethodName();
            long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
            System.out.println(String.format("Test %s took %d ms.", testName, elapsed));
        }
    };
    

    And then add JUnit @Rule annotation with your TimeTestWatcher for each test class:

    public class YourTest {
    
        @Rule
        public TimeTestWatcher watcher = new TimeTestWatcher();
    
        @Test
        public void testXXX() {}
    
        @Test
        public void testYYY() {}
    }
    

提交回复
热议问题