简体   繁体   English

无法使用junit测试异常

[英]Unable to test exception with junit

I have a method which contains a try-catch block and I don't know how to make my test pass... 我有一个包含try-catch块的方法,我不知道如何让我的测试通过...

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. 该方法的合同是捕获CustomException并将“Error Message”记录到外部组件:记录器。 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. 因此,您应该创建一个模拟记录器,将其提供给ClassToTest实例,测试该方法并验证是否已使用aright参数调用模拟记录器。

I personnally use EasyMock (and its "classextension" extension) to mock concrete classes, but there are other mock frameworks. 我个人使用EasyMock(及其“classextension”扩展)来模拟具体类,但还有其他模拟框架。 Read http://easymock.org/EasyMock3_0_Documentation.html for information about EasyMock and mocking in general. 有关EasyMock和一般模拟的信息,请阅读http://easymock.org/EasyMock3_0_Documentation.html

Your code is untestable without having a mock file in place. 如果没有模拟文件,您的代码将是不可测试的。 You can make this code more testable by mocking out external dependencies and using dependency injection (ie via guice ). 您可以通过模拟外部依赖项并使用依赖项注入(即通过guice )使此代码更易于测试。

If you're trying to test that CustomException is thrown under certain conditions, then you should be testing the code that throws the exception, rather than the code that catches it. 如果您正在尝试测试在某些条件下抛出CustomException,那么您应该测试抛出异常的代码,而不是捕获它的代码。 In your example, I'm guessing that your undefined "fileLoader" is what you're expecting to throw the exception? 在你的例子中,我猜你未定义的“fileLoader”是你期望抛出异常的东西?

If you're trying to test that the exception is caught and things continue to run smoothly, then you need to redesign ClassToTest so that a mock implementation of the potentially exception throwing class can be injected. 如果您正在尝试测试异常被捕获并且事情继续顺利运行,那么您需要重新设计ClassToTest,以便可以注入潜在异常抛​​出类的模拟实现。 That mock implementation would always throw the exception. 该模拟实现将始终抛出异常。 Then you can run through ClassToTest in your test and assert whatever condition indicates that it handled the exception properly. 然后,您可以在测试中运行ClassToTest并断言任何条件表明它正确处理了异常。

I think the right way to do this is pass your logger into your class, and if you're using a mocking framework like Mockito, you can verify your logger with verify : 我认为,要做到这一点是通过你的记录到你的类以正确的方式,如果你使用像一个的Mockito模拟框架,你可以验证你的记录验证

ClassToTest myInstance = new ClassToTest(myLogger);

// then, in your unit test
verify(myLogger).log("my log message")

the key here is passing in your dependencies so you can then verify interactions with them. 这里的关键是传递您的依赖项,以便您可以验证与它们的交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM