LoslegenKostenlos loslegen

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.

The necessary JUnit packages have been imported for you.

Diese Übung ist Teil des Kurses

Introduction to Testing in Java

Kurs anzeigen

Anleitung zur Übung

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

Interaktive Übung

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

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
        ____(actual)
    }
}
Code bearbeiten und ausführen