LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Introduction to Testing in Java

Kurs anzeigen

Anleitung zur Übung

  • 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.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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 bearbeiten und ausführen