gpt4 book ai didi

java - 使用 JUnit 测试异常。即使异常被捕获,测试也会失败

转载 作者:搜寻专家 更新时间:2023-11-01 01:09:20 24 4
gpt4 key购买 nike

我是 JUnit 测试的新手,我需要有关测试异常的提示。

我有一个简单的方法,如果它得到一个空输入字符串就会抛出异常:

public SumarniVzorec( String sumarniVzorec) throws IOException
{
if (sumarniVzorec == "")
{
IOException emptyString = new IOException("The input string is empty");
throw emptyString;
}

我想测试如果参数是空字符串,是否真的抛出了异常。为此,我使用以下代码:

    @Test(expected=IOException.class)
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
}
catch (IOException e)
{ // Error
e.printStackTrace();
}

结果是抛出异常,但是测试失败。我错过了什么?

谢谢你,托马斯

最佳答案

删除 try-catch block 。 JUnit 将收到异常并适本地处理它(根据您的注释,认为测试成功)。如果您抑制异常,则 JUnit 无法知道它是否被抛出。

@Test(expected=IOException.class)
public void testEmptyString() throws IOException {
new SumarniVzorec( "");
}

此外,jerry 博士 正确地指出,您不能将字符串与 == 运算符进行比较。使用 equals 方法(或 string.length == 0)

http://junit.sourceforge.net/doc/cookbook/cookbook.htm (请参阅“预期异常”部分)

关于java - 使用 JUnit 测试异常。即使异常被捕获,测试也会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3896614/

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