[英]How to check multiple exceptions with one JUnit Method?
i have this code in my program which is needed to be tested with jUnit 我的程序中有此代码,需要使用jUnit进行测试
void deleteCustomer(String name) throws UnknownCustomerException,
AccountNotEmptyException {
if (name == null) {
throw new NullPointerException();
} else if (!exists(name)) {
throw new UnknownCustomerException();
} else if (getCustomer(name).deletable()) {
customerList.remove(getCustomer(name));
}
}
I thought i can test it in one JUnit method like 我以为可以在一种JUnit方法中测试它
@Test
public void createCustomer(){
System.out.println("createCustomerTest");
try {
element.createCustomer(null);
//fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (NullPointerException anIndexOutOfBoundsException) {
assertTrue(anIndexOutOfBoundsException.getMessage().equals("NullPointerException"));
}
}
As you can see I already tried unsuccessfully to implement the NPE. 如您所见,我已经尝试实现NPE失败。 How can I check for several Exceptions in one JUnit Method?
如何在一个JUnit方法中检查几个异常? I checked some How-To's in the web but failed with that too.
我在网上检查了一些操作方法,但也失败了。
I think in your case you should have separate tests, however you can achieve this like so if using Java 8: 我认为在您的情况下,您应该进行单独的测试,但是如果使用Java 8,则可以像这样实现:
Using an AssertJ 3 assertion, which can be used alongside JUnit: 使用AssertJ 3断言,可以将其与JUnit一起使用:
import static org.assertj.core.api.Assertions.*;
@Test
public void test() {
Element element = new Element();
assertThatThrownBy(() -> element.createCustomer(null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("NullPointerException");
assertThatThrownBy(() -> element.get(1))
.isInstanceOf(IndexOutOfBoundsException.class);
}
It's better than @Test(expected=IndexOutOfBoundsException.class)
or .expect
syntax because it guarantees the expected line in the test threw the exception and lets you check more details about the exception, such as message. 它比
@Test(expected=IndexOutOfBoundsException.class)
或.expect
语法更好,因为它可以保证测试中的预期行引发异常,并允许您检查有关异常的更多详细信息,例如消息。
Write for each exception its own test. 为每个异常编写自己的测试。 It will be only one thrown at a time anyway.
无论如何一次只能扔一个。
For example a simplified method: 例如,一种简化方法:
void deleteCustomer( String name ) throws UnknownCustomerException
{
if ( name == null )
{
throw new NullPointerException();
}
else if ( !exists( name ) )
{
throw new UnknownCustomerException();
}
}
You have then two tests that each check if its exception is thrown: 然后,您有两个测试,每个测试都检查是否抛出了异常:
@Test( expected = NullPointerException.class )
public void deleteCustomer_shouldThrowNullpointerIfNameIsNull() throws UnknownCustomerException
{
String name = null;
cut.deleteCustomer( name );
}
@Test( expected = UnknownCustomerException.class )
public void deleteCustomer_shouldThrowUnknownCustomerExceptionIfNameIsUnknown() throws UnknownCustomerException
{
String name = "someUnknownName";
cut.deleteCustomer( name );
}
The problem with the NullpointerException is, that the test is true/successful/green if the NPE is thrown anywhere in the method - so you should make sure, that that is not happening for the test to be meaningful. NullpointerException的问题在于,如果将NPE抛出到方法中的任何位置,则测试为true / successful / green(绿色)-因此,您应确保对于有意义的测试不会发生这种情况。
You could add several "catch" statement into the test method for different exceptions, like: 您可以为不同的异常在测试方法中添加几个“ catch”语句,例如:
try {
element.createCustomer(null);
Assert.fail("Exception was expected!");
} catch (NullPointerException _ignore) {
} catch (UnknownCustomerException _ignore) {
}
or with Java
8
7 或使用Java
8
7
try {
element.createCustomer(null);
Assert.fail("Exception was expected!");
} catch (NullPointerException | UnknownCustomerException _ignore) {
}
But if you switch from JUnit to TestNG, then your test will be much cleaner: 但是,如果您从JUnit切换到TestNG,那么您的测试将更加简洁:
@org.testng.annotations.Test(expectedExceptions = { NullPointerException.class, UnknownCustomerException.class })
public void createCustomer() throws NullPointerException, UnknownCustomerException {
element.createCustomer(null);
}
More information about "expectedException" is here: http://testng.org/doc/documentation-main.html and example of the usage can be found here: http://www.mkyong.com/unittest/testng-tutorial-2-expected-exception-test/ 有关“ expectedException”的更多信息,请参见: http : //testng.org/doc/documentation-main.html ,用法示例可以在此处找到: http : //www.mkyong.com/unittest/testng-tutorial- 2个预期异常测试/
I suggest that you take a closer look at the JavaDoc of ExpectedException and implement different tests for different validations, eg 我建议您仔细查看ExpectedException的JavaDoc并为不同的验证实现不同的测试,例如
public class CustomerTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void throwsNullPointerExceptionForNullArg() {
exception.expect(NullPointerException.class);
element.createCustomer(null);
}
@Test
public void throwsUnknwonCustomerExceptionForUnkownCustomer() {
exception.expect(UnknownCustomerException.class);
// exception.expectMessage("Some exception message"); uncomment to verify exception message
element.createCustomer("unknownCustomerName");
}
@Test
public void doesNotThrowExceptionForKnownCustomer() {
element.createCustomer("a known customer");
// this test pass since ExpectedException.none() defaults to no exception
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.