JUnit code coverage switch statement with default branch

  Kiến thức lập trình

I have util method to process some text. The way of processing is determined by enum Mode. While writing unit test to cover this method, I had to add dummy enum element in order to include default part of switch statement into testing. Default part is my check for the case if enum is extended by new element and this new element is not added to switch statement meaning processing would be impossible for that new element. If I remove dummy element and try with null, then I get NPE and Java don’t even enter switch statement – which is normal behavior when you use null for switch statement.

The question: Is there a way to avoid adding dummy enum element but still cover default part of switch statement in unit test?

Code

abstract class LineBreaker {

    public enum Mode {
        LAST_SPACES,
        LAST_CHARS,
        DUMMY
    }

    public static String process(
        final String text,
        final LineBreaker.Mode mode,
        final int amount
    ) {
        switch (mode) {
            case LAST_SPACES : {
                // blah blah create `processingResult`
                return processingResult;
            }
            case LAST_CHARS : {
                // blah blah create `processingResult`
                return processingResult;
            }
            default :
                throw new IllegalStateException(
                    "Processor for " +
                        LineBreaker.class.getSimpleName() + "." +
                        LineBreaker.Mode.class.getSimpleName() + "." +
                        mode.name() +
                        " not implemented"
                );
        }
    }

}

Unit test

@Test
void testLineBreakerException() {
    assertThrows(
        IllegalStateException.class,
        () -> LineBreaker.process( "Dog", LineBreaker.Mode.DUMMY, 10 ),
        "Expected " + IllegalStateException.class.getSimpleName()
    );
}

LEAVE A COMMENT