gpt4 book ai didi

java - JUnit 测试代码在检查异常后停止执行

转载 作者:行者123 更新时间:2023-12-02 15:15:31 26 4
gpt4 key购买 nike

这是我的测试:

  import org.junit.rules.ExpectedException;
@Rule
public final ExpectedException exception = ExpectedException.none();

@Test
public void testSearch() {
List<Integer> myList = Arrays.asList(new Integer[] {1, 2, 4, 6, 3, 1, 2});
exception.expect(NoSuchElementException.class);
SimpleSearch.search(myList, 5);
System.out.println("here");

exception.expect(NoSuchElementException.class);
assertEquals(1, SimpleSearch.search(myList, 22));
}

当我运行它时,它说它运行了 1/1 但它不打印 here 并且它不做任何断言或运行 SimpleSearch.search(myList , 5); (异常被捕获后).

如何在捕获异常后让它继续(我想在同一个 testSearch 函数中执行)?

最佳答案

在这种情况下,您的测试应该更细化并拆分出 2 个测试用例

  @Test(ExpectedException=NoSuchElementException.class)
public void testSearch_NotFound() {
List<Integer> myList = Arrays.asList(new Integer[] {1, 2, 4, 6, 3, 1, 2});
SimpleSearch.search(myList, 5);
}

@Test
public void testSearch() {
List<Integer> myList = Arrays.asList(new Integer[] {1, 2, 4, 6, 3, 1, 2});
assertEquals(1, SimpleSearch.search(myList, 22));
}

关于java - JUnit 测试代码在检查异常后停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40878055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com