首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java:用Junit 3进行异常测试

Java:用Junit 3进行异常测试
EN

Stack Overflow用户
提问于 2012-11-06 05:56:57
回答 6查看 15.1K关注 0票数 19

我想为IndexOutOfBoundsException编写一个测试。请记住,我们应该使用JUnit 3。

我的代码:

代码语言:javascript
运行
AI代码解释
复制
public boolean ajouter(int indice, T element) {
    if (indice < 0 || indice > (maListe.size() - 1)) {
        throw new IndexOutOfBoundsException();
    } else if (element != null && !maListe.contains(element)) {
        maListe.set(indice, element);
        return true;
    }
}

经过一些研究,我发现您可以使用JUnit 4使用@Test(expected = IndexOutOfBoundsException.class)来完成这个任务,但是在JUnit 3中没有找到如何做到这一点的方法。

如何使用JUnit 3进行测试?

EN

回答 6

Stack Overflow用户

发布于 2012-11-06 06:01:35

在JUnit 3中测试异常使用以下模式:

代码语言:javascript
运行
AI代码解释
复制
try {
     ... code that should throw an exception ...

     fail( "Missing exception" );
} catch( IndexOutOfBoundsException e ) {
     assertEquals( "Expected message", e.getMessage() ); // Optionally make sure you get the correct message, too
}

如果代码没有抛出异常,fail()将确保得到错误。

我在JUnit 4中也使用这种模式,因为我通常希望确保异常消息中显示正确的值,而@Test不能这样做。

票数 36
EN

Stack Overflow用户

发布于 2012-11-06 06:00:55

基本上,如果方法没有抛出正确的异常,或者如果它抛出其他任何东西,则需要调用您的方法并失败:

代码语言:javascript
运行
AI代码解释
复制
try {
  subject.ajouter(10, "foo");
  fail("Expected exception");
} catch (IndexOutOfBoundException expect) {
  // We should get here. You may assert things about the exception, if you want.
}
票数 15
EN

Stack Overflow用户

发布于 2012-11-06 06:01:26

一个简单的解决方案是在unittest中添加一个try catch,并在未抛出异常时让测试失败

代码语言:javascript
运行
AI代码解释
复制
public void testAjouterFail() {
  try {
    ajouter(-1,null);
    JUnit.fail();
  catch (IndexOutOfBoundException()) {
    //success
  }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13252572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档