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

时间:2016-03-24 07:05:17

标签: java 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));
    }
}

我以为我可以在一个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方法中检查几个异常?我在网上检查了一些操作方法,但也失败了。

4 个答案:

答案 0 :(得分:6)

我认为在你的情况下你应该有单独的测试,但如果使用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 instructions here.

答案 1 :(得分:1)

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

    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,则测试为真/成功/绿色 - 因此您应该确保测试没有发生意义。

答案 2 :(得分:0)

你可以添加几个" 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-expected-exception-test/

答案 3 :(得分:0)

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