【问题标题】:How to measure time executed by a method called by a Junit 4 Test Case using Spring AOP or any other method如何使用 Spring AOP 或任何其他方法测量由 Junit 4 测试用例调用的方法执行的时间
【发布时间】:2016-06-20 09:24:55
【问题描述】:

我需要在 JUnit 4 测试框架中测量每个方法的方法执行时间。 考虑这个测试:

package org.test.libtest

import org.some.lib.Class
..
public class  testMyApp{
    @Test
    public void testSomething(){
        //Asume following method returns a Long value after doing a complex calc
        int a=100, b=100;
        Long ac=org.some.lib.Class.doSomething(int a, int b);
        Assert.assertEquals(100,ac);
    }   
    ..
    ..

}

要求是测量方法org.some.lib.Class.doSomething(..)执行的时间。

我们可以通过使用 Spring AOP 和 Junit 自己的 @Rule、Stopwatch 类的测试方法 testMyApp 来获取执行时间。 但是我们如何测量一个测试方法调用底层方法执行的时间呢?

【问题讨论】:

  • PerformanceMonitorInterceptor 之类的东西会为您做到这一点。

标签: java spring unit-testing junit aop


【解决方案1】:

您可以使用以下代码测量方法的执行时间

long startTime = System.currentTimeMillis();
// here is your method you want to measure
long estimatedTime = System.currentTimeMillis() - startTime; 

如果您想要更精确地测量时间,可以使用 System.nanoTime(); 而不是 System.currentTimeMillis();

【讨论】:

  • 看,我使用 AOP 来避免为每个 @Test 注释方法添加这些语句。适当的解决方案是,一个记录器,它会在执行测试方法时获取执行时间。重点是我不想修改现有的测试代码。
猜你喜欢
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-02
相关资源
最近更新 更多