[英]How can I get TestNG ITestResult in Spring test listener?
I'm writing tests using Spring and TestNG. 我正在使用Spring和TestNG编写测试。 An example of a test class:
一个测试类的例子:
@SpringBootTest
@TestExecutionListeners(
mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS,
listeners = {TestListener.class}
)
public class BaseTest extends AbstractTestNGSpringContextTests
{
}
My TestListener class extends TransactionalTestExecutionListener so I have override methods for beforeTestClass(TestContext testContext), afterTestMethod(TestContext testContext) etc. 我的TestListener类扩展了TransactionalTestExecutionListener,所以我有beforeTestClass(TestContext testContext),afterTestMethod(TestContext testContext)等的重写方法。
My problem is that within afterTestMethod I need to be able to get the TestNG ITestResult or TestResult so I can do different things depending on test success, fail or skip etc. Is there any way I can access ITestResult or TestResult from a spring test listener? 我的问题是,在afterTestMethod中,我需要能够获取TestNG ITestResult或TestResult,以便可以根据测试成功,失败或跳过等来做不同的事情。我可以从弹簧测试侦听器访问ITestResult或TestResult吗?
There is no easy direct way of getting access to the ITestResult
object of a test method that was executed because Spring doesn't seem to provide access to it. 没有简单的直接方法可以访问已执行的测试方法的
ITestResult
对象,因为Spring似乎没有提供对其的访问。
You can try doing something like this: 您可以尝试执行以下操作:
Method
object that represents a @Test
method that was just executed, it would query the current ITestContext
and find any ITestResult
object whose Method
object would match with the Method
object that was provided. @Test
方法的Method
对象时,它将查询当前的ITestContext
并查找其Method
对象与所提供的Method
对象匹配的任何ITestResult
对象。 ITestResult
object. ITestResult
对象。 Here's how a sample implementation could look like: 这是一个示例实现的样子:
public class MyListener extends TransactionalTestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
super.afterTestMethod(testContext);
ITestResult currentTestResult = getCorrespondingResultFor(testContext.getTestMethod());
}
private ITestResult getCorrespondingResultFor(Method method) {
ITestContext context = Reporter.getCurrentTestResult().getTestContext();
Set<ITestResult> allResults = new HashSet<>();
allResults.addAll(context.getPassedTests().getAllResults());
allResults.addAll(context.getFailedTests().getAllResults());
allResults.addAll(context.getSkippedTests().getAllResults());
return allResults
.stream()
.filter(result -> result.getMethod().getConstructorOrMethod().getMethod().equals(method))
.findAny()
.orElse(null);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.