ComeçarComece de graça

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.

Este exercício faz parte do curso

Introduction to Testing in Java

Ver curso

Instruções do exercício

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

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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
        ____ 
    }
}
Editar e executar o código