Failed to check exception using junit

I have a method that 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 an exception is thrown is to register it and it all works fine, how can I create a test that shows that it works?

I tried to capture the console output and

assertTrue(consoleOutput.contains("logMessgae") 

and this continued until I ran only this specific test case, but it did not work when I ran it in my test suite.

+3
source share
4 answers

, CustomException " " : . , , ClassToTest, , mock logger aright.

EasyMock ( "classextension" ), , . http://easymock.org/EasyMock3_0_Documentation.html EasyMock .

+2

. (.. guice).

0

, CustomException , , , , . , , undefined "fileLoader" - , ?

, , , ClassToTest, . . ClassToTest , , .

0
source

I think the right way to do this is to pass your registrar to your class, and if you use a mocking structure like Mockito, you can check your registrar to check :

ClassToTest myInstance = new ClassToTest(myLogger);

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

the key here is passed in your dependencies, so you can check the interaction with them.

0
source

Source: https://habr.com/ru/post/1791560/


All Articles