JUnit Assert.fail()方法示例

x33g5p2x  于2022-10-06 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(785)

在这篇文章中,我们将通过一个例子演示如何使用Assert.fail()方法。fail()方法属于JUnit 4org.junit.Assert类。

fail断言使抛出AssertionError的测试失败。它可以用来验证是否抛出了一个实际的异常,或者当我们想在开发过程中使测试失败。
请在https://www.javaguides.net/p/junit-5.html查看JUnit 5教程和例子。

JUnit 5中,所有的JUnit 4断言方法都被移到org.junit.jupiter.api.Assertions类中。

void org.junit.Assert.fail(String message)

用给定的消息使一个测试失败。 

参数。

  • message 识别AssertionError的信息(null可以)。

Assert.fail(String message) 方法实例

让我们首先创建*largest(final int[] list)*方法来寻找一个数组中最大的数字。

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class AssertFailExample {

 public int largest(final int[] list) {
      int index, max = Integer.MAX_VALUE;
      for (index = 0; index < list.length - 1; index++) {
         if (list[index] > max) {
             max = list[index];
         }
      }
      return max;
 }

让我们为上述*largest(final int[] list)*方法编写JUnit测试。

@Test
 public void testEmpty() {
     try {
         largest(new int[] {});
         fail("Should have thrown an exception");
     } catch (final RuntimeException e) {
         assertTrue(true);
     }
   } 
}

输出

相关文章

微信公众号

最新文章

更多