gpt4 book ai didi

java - 如何使用 @Rule 获取 JUnit 中的测试时间?

转载 作者:行者123 更新时间:2023-12-01 22:39:01 40 4
gpt4 key购买 nike

我有一个使用 JUnit 编写的测试类,我需要使用 @Rule 注释记录每个测试的时间。我怎样才能做到呢?我需要使用 StopWatch() 吗?

最佳答案

您可以使用这个示例:

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);
}
}

关于java - 如何使用 @Rule 获取 JUnit 中的测试时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58509194/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com