Try catch in a JUnit test

前端 未结 7 587
悲哀的现实
悲哀的现实 2020-12-04 23:21

I\'m writing unit tests for an application that already exists for a long time. Some of the methods I need to test are build like this:

public void someMetho         


        
7条回答
  •  天命终不由人
    2020-12-04 23:51

    What kind of exception is it? Is it

    1. an exception from doing something like using streams that won't happen in your unit test or
    2. an exception that can happen because of some kind of bad input?

    If it's 1. I would just put it at the method signature level because a try-catch is serving no real purpose other than ceremony.

    @Test
    public void testFoo() throws Exception {
        // ...
    }
    

    If it's 2. it becomes a little more complicated. You need to ask yourself what should be happening if the Exception is thrown. Should the test fail? Is it expected? Is it irrelevant? Examples below of how to handle all of these. BEWARE: I only used Exception because you did. I hope it really isn't though because if it's possible for some other exception to be thrown other than the expected then these will be very wonky. If possible don't use Exception, use something more specific (in the junit and code).

    // The below code assumes you've imported the org.junit.Assert class.
    
    @Test
    public void thisShouldFailIfExceptionCaught() {
        //Given...
        try {
            // When...
        } catch (Exception e) {
            Assert.fail();
        }
        // Then...
    }
    
    @Test
    public void thisShouldPassOnlyIfTheExceptionIsCaught() {
        //Given...
        try {
            // When...
            Assert.fail();
        } catch (Exception expected) {}
        // No "then" needed, the fact that it didn't fail is enough.
    }
    
    @Test
    public void irrelevantExceptionThatCouldBeThrown() {
        //Given...
        try {
            // When...
        } catch (Exception e) {}
        // Then...
    }
    

提交回复
热议问题