问题描述
我可以使用以下方法对测试失败执行操作:
I can perform actions on test failure by using:
@After
public void afterTest(Scenario scenario) {
if (scenario.isFailed()) {
/*Do stuff*/
}
}
然而,我需要执行的一些操作取决于抛出的异常以及抛出的上下文。有没有办法让Throwable导致测试失败?例如,在JUnit中我会通过扩展TestWatcher并在我的测试中添加规则来实现:
However some of the actions I need to perform depend on the Exception that was thrown and in what context it was thrown. Is there a way to get the Throwable that caused the test to fail? For example in JUnit I would do this by extending TestWatcher and add a rule to my tests:
@Override
protected void failed(Throwable e, Description description) {
/*Do stuff with e*/
}
然而,黄瓜junit iplementation不允许使用规则,所以这个解决方案不适用于Cucumber。
However the cucumber-junit iplementation does not allow the use of rules, so this solution would not work with Cucumber.
我不认为我需要解释为什么在测试失败时访问抛出的异常会有用,但是我仍然会提供一个示例:
I don't think I need to explain why accessing a thrown exception on test failure would be useful, however I will still provide an Example:
我的测试环境并不总是稳定的,所以我的测试可能会在任何时候都意外地失败(我没有特定的地方可以尝试捕捉异常,因为它可能随时发生)。当发生这种情况时,我需要测试重新安排进行另一次尝试,并记录事件,以便我们可以获得有关环境不稳定性的详细统计数据(何时,多久,多长时间等)。
My test environment is not always stable, so my tests might fail unexpectedly at any moment (there's no specific place I can try to catch the exception since it could occur at any time). When this happens I need the test to reschedule for another attempt, and log the incident so that we can get some good statistical data on the environment instability (when, how frequent, how long etc.)
推荐答案
我已经使用反射实现了这个方法。您无法直接访问步骤错误(堆栈跟踪)。我创建了这个静态方法,允许您访问stepResults属性,然后您可以迭代并获取错误并执行您想要的任何操作。
I've implemented this method using reflections. You can't access directly to steps errors (stack trace). I've created this static method which allows you to access to "stepResults" attribute and then you can iterate and get the error and do whatever you want.
@After
public void afterScenario(Scenario scenario) {
if (scenario.isFailed())
logError(scenario);
}
private static void logError(Scenario scenario) {
Field field = FieldUtils.getField(((ScenarioImpl) scenario).getClass(), "stepResults", true);
field.setAccessible(true);
try {
ArrayList<Result> results = (ArrayList<Result>) field.get(scenario);
for (Result result : results) {
if (result.getError() != null)
LOGGER.error("Error Scenario: {}", scenario.getId(), result.getError());
}
} catch (Exception e) {
LOGGER.error("Error while logging error", e);
}
}
这篇关于如何获取在Java中Cucumber测试失败时抛出的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!