Aan de slagGa gratis aan de slag

Handling Exceptions: Message Processing

Just as using and handling exceptions is an integral part of writing code, testing these exceptions is vital to testing your project.

In this exercise, you will practice the syntax of JUnit's class instance assertion. You are given a method which converts a string to uppercase, but throws a custom RuntimeException if the string is null. The task is to write unit tests for it.

Deze oefening maakt deel uit van de cursus

Introduction to Testing in Java

Cursus bekijken

Oefeninstructies

  • Assert the message has been converted to uppercase in the success scenario test.
  • Use the correct kind of assertion to verify that the exception thrown is an instance of the RuntimeException class.
  • Enter the expected class of the exception.
  • Use the correct assertion to verify the exception message.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

public class Main {
    public static void main(String[] args) {
		launchTestsAndPrint(MessageProcessorTest.class);
    }
}

class MessageProcessorTest {

    @Test
    void processMessage_returnsUppercase() {
        String message = "error!";
        String expected = "ERROR!";

        String actual = MessageProcessor.processMessage(message);
		
        // Assert the message is converted to uppercase
        ____(expected, actual);
    }

    @Test
    void processMessage_throwsException_whenMessageIsNull() {
        String message = null;
        Exception expectedException = null;

        try {
        	MessageProcessor.processMessage(message);
        } catch (Exception e) {
        	expectedException = e;
        }
        // Assert the correct type of exception
        ____(RuntimeException.class, expectedException);
        // Assert the correct exception message
        ____("Message cannot be null.", expectedException.getMessage());
    }
}
Code bewerken en uitvoeren