Get startedGet started for free

Username validation

You are writing the signup form for your website and you are currently working on the username validation. It's a boolean true/false method, however it has many branches and you want to make sure they can all be reached and will behave as expected.

To fully verify this method, you need to write multiple tests, one for each type of scenario. Fortunately, this is not too complicated.

This exercise is part of the course

Introduction to Testing in Java

View Course

Exercise instructions

  • Enter a username that is too short (less than 3 characters) and will fail the validation in the test that verifies the username length check.
  • Pass the username to the .isValidUsername() method and store the result.
  • Assert that the null case fails username validation.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import org.junit.jupiter.api.Test;
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) {
                return username != null && !username.isEmpty() && !username.contains(" ") && username.length() >= 3;
    }
}

class UsernameValidatorTest {

    @Test
    void isValidUsername_returnsTrue_whenValidUsername() {
        String username = "john_doe";
        boolean actual = UsernameValidator.isValidUsername(username);
        assertTrue(actual);
    }

    @Test
    void isValidUsername_returnsFalse_whenSpaces() {
        String username = "john doe";
        boolean actual = UsernameValidator.isValidUsername(username);
        assertFalse(actual);
    }

    @Test
    void isValidUsername_returnsFalse_whenShortUsername() {
        // Enter a username that is too short
        String username = "____";
        boolean actual = UsernameValidator.isValidUsername(username);
        assertFalse(actual);
    }

    @Test
    void isValidUsername_returnsFalse_whenNull() {
    	String username = null;
        // Pass the username to isValidUsername 
        boolean actual = UsernameValidator.____;
        // Verify the username is invalid
        ____ 
    }
}
Edit and Run Code