繁体   English   中英

如何使用一个JUnit方法检查多个异常?

[英]How to check multiple exceptions with one JUnit Method?

我的程序中有此代码,需要使用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));
    }
}

我以为可以在一种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"));
    }
}

如您所见,我已经尝试实现NPE失败。 如何在一个JUnit方法中检查几个异常? 我在网上检查了一些操作方法,但也失败了。

我认为在您的情况下,您应该进行单独的测试,但是如果使用Java 8,则可以像这样实现:

使用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);
}

它比@Test(expected=IndexOutOfBoundsException.class).expect语法更好,因为它可以保证测试中的预期行引发异常,并允许您检查有关异常的更多详细信息,例如消息。

Maven / Gradle说明在这里。

为每个异常编写自己的测试。 无论如何一次只能扔一个。
例如,一种简化方法:

    void deleteCustomer( String name ) throws UnknownCustomerException
    {
        if ( name == null )
        {
            throw new NullPointerException();
        }
        else if ( !exists( name ) )
        {
            throw new UnknownCustomerException();
        }
    }

然后,您有两个测试,每个测试都检查是否抛出了异常:

@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 );
}

NullpointerException的问题在于,如果将NPE抛出到方法中的任何位置,则测试为true / successful / green(绿色)-因此,您应确保对于有意义的测试不会发生这种情况。

您可以为不同的异常在测试方法中添加几个“ catch”语句,例如:

try {
    element.createCustomer(null);

    Assert.fail("Exception was expected!");
} catch (NullPointerException _ignore) {
} catch (UnknownCustomerException _ignore) {
}

或使用Java 8 7

try {
    element.createCustomer(null);

    Assert.fail("Exception was expected!");
} catch (NullPointerException | UnknownCustomerException _ignore) {
}

但是,如果您从JUnit切换到TestNG,那么您的测试将更加简洁:

@org.testng.annotations.Test(expectedExceptions = { NullPointerException.class, UnknownCustomerException.class })
public void createCustomer() throws NullPointerException, UnknownCustomerException {
    element.createCustomer(null);
}

有关“ expectedException”的更多信息,请参见: http//testng.org/doc/documentation-main.html ,用法示例可以在此处找到: http//www.mkyong.com/unittest/testng-tutorial- 2个预期异常测试/

我建议您仔细查看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.

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