黄瓜JVM:测试是否抛出正确的异常 [英] Cucumber JVM: Test if the correct exception is thrown
问题描述
在使用Cucumber JVM时如何测试是否抛出了正确的异常?使用JUnit时,我会执行以下操作:
How to test that the correct exception is thrown when using Cucumber JVM? When using JUnit, I would do something like this:
@Test(expected = NullPointerException.class)
public void testExceptionThrown(){
taskCreater.createTask(null);
}
这很优雅。但是,当使用黄瓜JVM时,我如何才能达到同样的优雅呢?我的测试现在看起来像这样:
As you can see, this is very elegant. But how can I achieve the same elegance, when using cucumber JVM? My test looks like this right now:
@Then("the user gets a Null pointer exception$")
public void null_exception_thrown() {
boolean result = false;
try {
taskCreater.createTask(null);
} catch (NullPointerException e) {
result = true;
}
assertTrue(result);
}
请注意需要尝试
.. catch
,后跟标志上的 assertTrue
。
Note the need for a try
..catch
followed by an assertTrue
on a flag.
推荐答案
测试不快乐的路径可能很困难。这是我发现用黄瓜做的一种好方法。
Testing the not-happy-path can be hard. Here's a nice way that I've found to do it with cucumber.
Scenario: Doing something illegal should land you in jail
Then a failure is expected
When you attempt something illegal
And it fails.
好,别开枪打我,因为我放了然后
在 When
之前,我只是认为它读起来更好,但您不必这样做。
OK, don't shoot me because I put the Then
before the When
, I just think it reads better but you don't have to do that.
我将异物存储在(黄瓜范围内的)世界对象中,但是您也可以在步骤文件中进行此操作,但这会在以后限制您。
I store my excepions in a (cucumber-scoped) world object, but you could also do it in your step file, but this will limit you later.
public class MyWorld {
private boolean expectException;
private List<RuntimeException> exceptions = new ArrayList<>();
public void expectException() {
expectException = true;
}
public void add(RuntimeException e) {
if (!expectException) {
throw e;
}
exceptions.add(e);
}
public List<RuntimeException> getExceptions() {
return exceptions;
}
}
您的步骤非常简单:
@Then("a failure is expected")
public void a_failure_is_expected() {
myWorld.expectException();
}
在您(至少有时)期待例外的步骤中,抓住
In a step where you are (at least sometimes) expecting an exception, catch it and add it to the world.
@When("you attempt something illegal")
public void you_attempt_something_illegal() {
try {
myService.doSomethingBad();
} catch (RuntimeException e) {
world.add(e);
}
}
现在,您可以检查是否在
Now you can check whether the exception was recorded in the world.
@And("it fails")
public void it_fails() {
assertThat(world.getExceptions(), is(not(empty()));
}
这种方法最有价值的是,当您不期望它时,它不会吞下异常。
The most valuable thing about this approach is that it won't swallow an exception when you don't expect it.
这篇关于黄瓜JVM:测试是否抛出正确的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!