Username Validation Parameterized
As your Java knowledge increases, you've decided to revisit the username validator from Chapter 1. Since it depends on a single output, it can be shortened using parameterization.
Consider all the failure outcomes of the isValidUsername()
method. Condense them all in a single @ParameterizedTest
.
This exercise is part of the course
Introduction to Testing in Java
Exercise instructions
- Use the correct annotation to mark a test as a parameterized test.
- Add a null input to the test.
- Add the annotation to input values into the test.
- Mark the value type of the inputs.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.*;
import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchTestsAndPrint;
import static org.junit.jupiter.api.Assertions.*;
public class Main {
public static void main(String[] args) {
launchTestsAndPrint(UsernameValidatorTest.class);
}
}
class UsernameValidator {
public static boolean isValidUsername(String username) {
if (username == null || username.isEmpty() || username.contains(" ")) {
return false;
}
return username.length() >= 3;
}
}
class UsernameValidatorTest {
// Annotate with the correct annotation for parameterized test
@____
// Add the annotation for inputting a null input
@____
// Add the annotation for inputting values and the type of the inputs
@____(____ = {"john doe", "jd"})
void isValidUsername_returnsFalse_whenSpaces(String username) {
boolean actual = UsernameValidator.isValidUsername(username);
assertFalse(actual);
}
}