gpt4 book ai didi

java - 如何排除@AfterClass方法所花费的时间?

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:10 25 4
gpt4 key购买 nike

我运行了以下测试类,它报告第一个测试花了 2 秒,第二个测试花了 4 秒。我希望 JUnit 输出每个测试用例的时间,而不考虑 @BeforeClass@AfterClass 方法的时间。

但显然它只将 @AfterClass 方法的时间包含到最后一个测试用例中,如果你问我的话,这根本没有意义。

有没有办法让 JUnit 只输出每个测试用例所花费的时间?

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TimeTest {
@Test
public void test1() throws InterruptedException {
Thread.sleep(2000);
}

@Test
public void test2() throws InterruptedException {
Thread.sleep(2000);
}

@AfterClass
public static void afterClass() throws InterruptedException {
Thread.sleep(2000);
}
}

最佳答案

@BeforeClass@AfterClass 运行所有测试

你应该做的是在实例变量的帮助下使用@BeforeAfter

public class TimeTest {

long timeInMillis=0;

@Before
public void before(){
timeInMillis = System.currentTimeMillis();
}

@Test
public void test1() throws InterruptedException {
Thread.sleep(2000);
}

@Test
public void test2() throws InterruptedException {
Thread.sleep(2000);
}

@After
public static void after() throws InterruptedException {
long diff = System.currentTimeMillis() - timeInMillis;
// log the diff or cast it to seconds
}
}

关于java - 如何排除@AfterClass方法所花费的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57079436/

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