Exercise: Email Address Validator

Understand how to implement robust validation of email addresses based on specified criteria using TDD.

We'll cover the following

Task and requirements

Imagine you’re developing a class EmailValidator that checks the validity of email addresses. Your task is to write test cases for the EmailValidator class' validation methods using JUnit, following the TDD approach.

Here are the simplified requirements for this exercise:

  • Create a Java class called EmailValidator with the public boolean isValidEmail(String email) method. This method should take an email address as a string and return true if the email is valid, according to the following rules:

    • The email address should contain exactly one "@" symbol.

    • The "@" symbol should not be the first or last character in the email.

    • The email address should have at least one character before and after the "@" symbol.

    • The domain part (after the "@" symbol) should have at least one "." character.

    • The email address should not contain spaces.

  • Your challenge is to write test cases for the isValidEmail() method following the Arrange, Act, and Assert structure. Write test cases that cover various scenarios, including valid and invalid email addresses.

  • Implement the tests before implementing the isValidEmail() method in the EmailValidator class. The tests should initially fail because the method is not implemented.

  • Implement the isValidEmail() method to make the tests pass.

Try it yourself

Implement your solution in the widget below:

Get hands-on with 1400+ tech skills courses.