无法使用junit测试异常 [英] Unable to test exception with junit

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

问题描述

我有一个包含try-catch块的方法,我不知道如何通过测试...

这是我的代码:

public class ClassToTest {
    public void loadFileContent() {
        try {
            InputStream fileStream = fileLoader.loadFileContent();
            fileContentReader = new BufferedReader(new InputStreamReader(fileStream));
        } catch(CustomException ce) {
            logger.log(Level.SEVERE, "Error message")
        }
    }
}

public class TestClassToTest {
    @Test
    (expected = CustomException.class)
    public void testCustomException() throws Exception {
        loadFileContent();
    }
}

抛出异常时,我唯一想做的就是记录它,并且一切正常,但是,如何创建一个测试来证明其正常工作呢?

我试图捕获控制台输出和

assertTrue(consoleOutput.contains("logMessgae") 

并且只要我只运行那个特定的测试用例就可以使用,但是当我在测试套件中运行它时就不起作用了.

解决方案

该方法的约定是捕获CustomException并将错误消息"记录到外部组件:记录器中.因此,您应该创建一个模拟记录器,将其提供给ClassToTest实例,测试该方法并验证是否已使用正确的参数调用了模拟记录器.

我个人使用EasyMock(及其"classextension"扩展名)来模拟具体的类,但是还有其他模拟框架.阅读 http://easymock.org/EasyMock3_0_Documentation.html 了解有关EasyMock和一般模拟的信息. >

I have a method which contains a try-catch block and I don't know how to make my test pass...

Here is my code:

public class ClassToTest {
    public void loadFileContent() {
        try {
            InputStream fileStream = fileLoader.loadFileContent();
            fileContentReader = new BufferedReader(new InputStreamReader(fileStream));
        } catch(CustomException ce) {
            logger.log(Level.SEVERE, "Error message")
        }
    }
}

public class TestClassToTest {
    @Test
    (expected = CustomException.class)
    public void testCustomException() throws Exception {
        loadFileContent();
    }
}

The only thing I want to do when the exception is thrown is to log it, and that all works great, however, how can I create a test that shows that it works?

I tried to capture console output and

assertTrue(consoleOutput.contains("logMessgae") 

and that worked as long as I ran only that specific test case, but it did not work when I ran it in my test suite.

解决方案

The contract of the method is to catch CustomException and log "Error Message" to an external component : the logger. You should thus create a mock logger, give it to the ClassToTest instance, test the method and verify that the mock logger has been called with the aright arguments.

I personnally use EasyMock (and its "classextension" extension) to mock concrete classes, but there are other mock frameworks. Read http://easymock.org/EasyMock3_0_Documentation.html for information about EasyMock and mocking in general.

这篇关于无法使用junit测试异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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