gpt4 book ai didi

java - junit,获取失败的方法名

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:07:12 25 4
gpt4 key购买 nike

我正在使用 Junit,我想在测试失败时记录测试方法名称和一些堆栈跟踪,有没有办法做到这一点?

下面是我的示例代码:

public class TestGoogleHomePage extends Browser {

@Test
public void testLoadGoogle() {
...............
//assume this case will fail
}

@Test
public void testSearchGoogle() {
.......
}

@Rule
public TestWatcher watchman = new TestWatcher() {

@Override
protected void failed(Throwable e, Description description) {
System.out.println("test fail");
System.out.println(Thread.currentThread().getStackTrace()[1]
.getMethodName());
}

@Override
protected void succeeded(Description description) {
......

}
};

声明 System.out.println(Thread.currentThread().getStackTrace()[1] .getMethodName()); 将打印方法失败,而不是 testLoadGoogle。有没有一种方法可以改为捕获失败方法的名称?

我还可以打印堆栈跟踪吗?

另外,如果我能避免在实际测试中为此目的添加额外的代码,那就太好了。因为我不想为我的每个测试用例重复这些代码。

预先感谢您的帮助。

最佳答案

Description 类有一个 getMethodName()声明的方法

Returns

If this describes a method invocation, the name of the method (or null if not)

就这么叫吧

System.out.println(description.getMethodName());

关于java - junit,获取失败的方法名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919375/

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