使用JUnit测试异常。即使异常被捕获,测试失败 [英] Testing for Exceptions using JUnit. Test fails even if the Exception is caught

查看:688
本文介绍了使用JUnit测试异常。即使异常被捕获,测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚用JUnit进行测试,我需要一个关于测试异常的提示。



我有一个简单的方法,如果获取一个空的输入字符串:

  public SumarniVzorec(String sumarniVzorec)throws IOException 
{
if(sumarniVzorec ==)
{
IOException emptyString = new IOException(输入字符串为空);
throw emptyString;
}

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

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

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



谢谢Tomas

解决方案

删除 try-catch block。 JUnit将收到异常并适当处理(考虑测试成功,根据您的注释)。如果你拒绝异常,那么如果JUnit被抛出,就无法知道JUnit。

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

另外, dr jerry 正确地指出你不能将字符串与 == 运算符进行比较。使用等于方法(或 string.length == 0



http://junit.sourceforge.net/doc/cookbook/cookbook.htm (见预期例外部分)


I am new to testing with JUnit and I need a hint on testing Exceptions.

I have a simple method that throws an exception if it gets an empty input string:

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

I want to test that the exception is actually thrown if the argument is an empty string. For that, I use following code:

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

The result is that the exception is thrown, but the test fails. What am I missing?

Thank you, Tomas

解决方案

Remove try-catch block. JUnit will receive exception and handle it appropriately (consider test successful, according to your annotation). And if you supress exception, there's no way of knowing for JUnit if it was thrown.

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

Also, dr jerry rightfully points out that you can't compare strings with == operator. Use equals method (or string.length == 0)

http://junit.sourceforge.net/doc/cookbook/cookbook.htm (see 'Expected Exceptions' part)

这篇关于使用JUnit测试异常。即使异常被捕获,测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆