我在我的程序中有这个代码,需要使用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));
}
}
Run Code Online (Sandbox Code Playgroud)
我想我可以在一个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"));
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我已经尝试过实施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);
}
Run Code Online (Sandbox Code Playgroud)
它比@Test(expected=IndexOutOfBoundsException.class)或.expect语法更好,因为它保证测试中的预期行抛出异常,并让您检查有关异常的更多详细信息,例如消息.
| 归档时间: |
|
| 查看次数: |
6662 次 |
| 最近记录: |