简体   繁体   English

Java junit断言已引发异常

[英]Java junit assert that an exception has thrown

Is one better than the other? 这个比那个好吗? if so, for what reasons? 如果是这样,出于什么原因? I am leaning towards the first because i can understand what the test is trying to much more quickly. 我倾向于第一个,因为我可以更快地了解测试的目的。

If so, when should one be using assertThrows() ? 如果是这样,什么时候应该使用assertThrows()

@Test(expected=CustomException.class)
public void test_one() {
   execute()
}

vs.

@Test
public void test_one() {
    assertThrows(CustomException.class, () -> execute());
}

Lets say you have your test this way: 假设您以这种方式进行测试:

@Test
public void test_one() {
   execute1();
   execute2()
}

Assume you want to check CustomException thrown by execute2(). 假设您要检查execute2()引发的CustomException

Now if you go with the first approach, and execute1() throws the CustomException test will still pass and you won't be able to know whether it was thrown by execute2() or not. 现在,如果您采用第一种方法,则execute1()引发的CustomException测试仍将通过,您将无法知道它是否由execute2()引发。

But with the second approach you can specify that you want to make sure that exception is thrown by execute2() method call, hence test will only pass when the CustomException is thrown by execute2() method. 但是,使用第二种方法时,您可以指定要确保由execute2()方法调用引发了异常,因此,只有在由execute2()方法引发CustomException时,测试才会通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM