Categories: Unit Testing

JUnit Tests Code Samples for Testing Exception Scenarios

The article presents an example of unit tests which tests both happy path and exception scenario.
Business Requirement
  • User trying to open an account must be validated against the business rules related with users’ registration.
  • Following are different business rules:
    • User must provide a valid email address
    • User must provide his first name
    • User’s age must be 18 and above

 

Class Design

To demonstrate the unit tests with happy and exception scenarios, following classes have been shown below:

  • SignupValidation: Consists of code validating business rules
  • SignupException: Custom exception representing Signup business rules failure
  • EmailValidator (Get the code from this page).
  • SignupValidationTests: Unit tests for testing signup validation code

Class SignupValidation

The class consists of the three validateXXX methods to validate three different business rules mentioned above. The need is to test these three validation methods in the unit tests.

public class SignupValidation {

 private EmailValidator emailValidator;

 public SignupValidation() {  
  emailValidator = new EmailValidator();
 }

 public boolean validate( User u ) throws SignupException{
  validateEmailAddress( u.getEmailAddress() );
  validateAge( u.getAge() );
  validateFirstName( u.getFirstName() );
  return true;
 }

 public boolean validateFirstName(String firstName)  throws SignupException {
  if( firstName.trim().length() == 0 ) {
   throw new SignupException( "Firstname can not be empty" );
  }
  return true;
 }

 public boolean validateEmailAddress( String email ) throws SignupException {
  boolean isValid = emailValidator.validate( email );
  if( !isValid ) {
   throw new SignupException( "Invalid email address" );
  }
  return isValid;
 }

 public boolean validateAge( int age )  throws SignupException  {
  if( age < 18 ) {
   throw new SignupException( "Age must be 18 and above" );
  }
  return true;
 }

}

Class SignupValidationTest

The unit tests consist of methods to test both, happy path and the exception scenarios. Take a look at following for details:

  • validateValidFirstName: This tests the happy path when users enter the valid first name. In case, there is a change in business rule due to which exception thrown is caught, the unit test fails. See the code, “fail( e.getMessage() )
  • validateInvalidFirstName: This tests the exception scenario when users enter invalid first name. As a result, the validateFirstName method in SignupValidation class throws exception. Here, in unit test, the exception thrown is matched with expected exception class. See the code, “@Test( expected = SignupException.class)
public class SignupValidationTest {

 private SignupValidation sv;
 private User u;

 @Before
 public void setUp() throws Exception {
  sv = new SignupValidation();  
 }

 @After
 public void tearDown() throws Exception {
  sv = null;
 }

 @Test
 public void testPassedValidation() {
  User u = new User();
  u.setEmailAddress( "xyz@gmail.com" );
  u.setFirstName( "Chris" );
  u.setAge( 20 );

  try {
   sv.validate( u );      
  } catch (SignupException e) {
   fail( e.getMessage() );
  }
 }

 @Test (expected = SignupException.class)
 public void testFailedValidation()  throws SignupException  {
  User u = new User();
  u.setEmailAddress( "xyz@gmail.com" );
  u.setFirstName( "Chris" );
  u.setAge( 16 );

  sv.validate( u );          

 }

 @Test
 public void validateValidFirstName()  {    
  try {
   sv.validateFirstName( "Chris" );      
  } catch (SignupException e) {
   fail( e.getMessage() );
  }

 }

 @Test (expected = SignupException.class) 
 public void validateInvalidFirstName() throws SignupException {
  sv.validateFirstName( "" );
  sv.validateFirstName( "    " );
 }

 @Test
 public void validateValidEmailAddress()  {    
  try {
   sv.validateEmailAddress( "xyz@gmail.com" );      
  } catch (SignupException e) {
   fail( e.getMessage() );
  }

 }

 @Test (expected = SignupException.class) 
 public void validateInvalidEmailAddress() throws SignupException {
  sv.validateEmailAddress( "xyz@gmail." );
  sv.validateEmailAddress( "xyzgmail.com" );
  sv.validateEmailAddress( "gmail.com" );
  sv.validateEmailAddress( "gmail" );
  sv.validateEmailAddress( "@gmail.com" );
 }

 @Test
 public void validateAgeGreaterThan17()  {    
  try {
   sv.validateAge( 18 );      
  } catch (SignupException e) {
   fail( e.getMessage() );
  }

 }

 @Test (expected = SignupException.class) 
 public void validateAgeLessThan18() throws SignupException {
  sv.validateAge( 17 );
 }

}

Class SignupException

public class SignupException extends Exception {

 public SignupException( String message ) {
  super( message );
 }
}
[adsenseyu1]
Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

Share
Published by
Ajitesh Kumar
Tags: Unit Testing

Recent Posts

Coefficient of Variation in Regression Modelling: Example

When building a regression model or performing regression analysis to predict a target variable, understanding…

3 days ago

Chunking Strategies for RAG with Examples

If you've built a "Naive" RAG pipeline, you've probably hit a wall. You've indexed your…

1 week ago

RAG Pipeline: 6 Steps for Creating Naive RAG App

If you're starting with large language models, you must have heard of RAG (Retrieval-Augmented Generation).…

2 weeks ago

Python: List Comprehension Explained with Examples

If you've spent any time with Python, you've likely heard the term "Pythonic." It refers…

2 weeks ago

Large Language Models (LLMs): Four Critical Modeling Stages

Large language models (LLMs) have fundamentally transformed our digital landscape, powering everything from chatbots and…

3 months ago

Agentic Workflow Design Patterns Explained with Examples

As Large Language Models (LLMs) evolve into autonomous agents, understanding agentic workflow design patterns has…

3 months ago