Testing Exceptions Practice
Svep för att visa menyn
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.
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.
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);
});
}
}
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal