Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Testing Exceptions Practice | Exceptions
Java JUnit Library. Types of Testing

Testing Exceptions Practice

Deslize para mostrar o menu

I hope you remember how you wrote exception handling in this chapter. It's time to practice writing tests for these assertions.

Task

Your task is to cover two methods from the ExceptionHandlingExercise class with tests using assertThrows() and assertDoesNotThrow() assertions in the unit test class that I have created for you.

Link to the Task

Hint
expand arrow

Pay attention to the names of the unit tests; your task is to implement them so that they perform the function indicated in the name.

At the beginning of each test, you need to create an instance of the ExceptionHandlingExercise class.

It will look like this: ExceptionHandlingExercise exercise = new ExceptionHandlingExercise();.

Next, you need to create a variable that will hold the value you want to test. For example: int underage = 17;.

Use the assertions you learned in the previous chapter.

You can optionally write additional tests for the functionality of these methods.

Solution
expand arrow
package codefinity;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;

public class ExceptionHandlingExerciseTest {

    @Test
    public void checkAge_ShouldThrowIllegalArgumentException_WhenAgeIsLessThan18() {
        ExceptionHandlingExercise exercise = new ExceptionHandlingExercise();
        int underage = 17;

        assertThrows(IllegalArgumentException.class, () -> {
            exercise.checkAge(underage);
        });
    }

    @Test
    public void checkAge_ShouldNotThrowException_WhenAgeIs18OrMore() {
        ExceptionHandlingExercise exercise = new ExceptionHandlingExercise();
        int legalAge = 18;

        assertDoesNotThrow(() -> {
            exercise.checkAge(legalAge);
        });
    }

    @Test
    public void printLength_ShouldThrowNullPointerException_WhenStringIsNull() {
        ExceptionHandlingExercise exercise = new ExceptionHandlingExercise();
        String nullString = null;

        assertThrows(NullPointerException.class, () -> {
            exercise.printLength(nullString);
        });
    }

    @Test
    public void printLength_ShouldNotThrowException_WhenStringIsNotNull() {
        ExceptionHandlingExercise exercise = new ExceptionHandlingExercise();
        String nonNullString = "JUnit";

        assertDoesNotThrow(() -> {
            exercise.printLength(nonNullString);
        });
    }
}
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 7

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 3. Capítulo 7
some-alt