Skip to content
Related Articles
Open in App
Not now

Related Articles

JUnit – Testcases for Credit Card Validation as a Maven Project

Improve Article
Save Article
Like Article
  • Last Updated : 15 Nov, 2022
Improve Article
Save Article
Like Article

In this article let us see a much-required functionality that is credit card validation as well as its relevant JUnit test cases for given credit card numbers. In an e-commerce project, credit card payment is the valid and much desired required functionality. We need to have a proper validation mechanism for that. So, by using the “Luhn algorithm”, the validation code is done. As a maven project, let us cover the validation as well as the JUnit test case part.

Sample Maven Project

Project Structure:

Project Structure


Dependencies need to be specified in 



<?xml version="1.0" encoding="UTF-8"?>
        <!-- junit 5, unit test -->
                <!-- -->
                <!-- Need this to support JUnit 5 -->

Now let us write the business logic of validating a credit card


public class CreditCardValidation {   
    /* Return true if the card number is valid by using Luhn algorithm.
        A credit card number must have between 13 and 16 digits. 
        It must start with:
        4 for Visa cards
        5 for Master cards
        37 for American Express cards
        6 for Discover cards
    public static boolean checkForValidity(long number)
       return (getNumberOfDigits(number) >= 13 &&
               getNumberOfDigits(number) <= 16) &&
               (checkForPrefixMatching(number, 4) ||
                checkForPrefixMatching(number, 5) ||
                checkForPrefixMatching(number, 37) ||
                checkForPrefixMatching(number, 6)) &&
              ((sumOfDoubleEvenPlaces(number) +
                getSumOfOddPlaces(number)) % 10 == 0);
    // Get the result from Step 2
    public static int sumOfDoubleEvenPlaces(long inputNumber)
        int summation = 0;
        String number = inputNumber + "";
        for (int i = getNumberOfDigits(inputNumber) - 2; i >= 0; i -= 2)
            summation += getTheDigits(Integer.parseInt(number.charAt(i) + "") * 2);
        return summation;
    // When the input number is a single digit that 
    // means between 0 to 9, Return this number as it is
    // If not, 
    // return the sum of the two digits
    public static int getTheDigits(int inputNumber)
        if (inputNumber < 9)
            return inputNumber;
        return inputNumber / 10 + inputNumber % 10;
    // We are going to add the odd-place digits 
      // in number and return their sum
    public static int getSumOfOddPlaces(long inputnumber)
        int summation = 0;
        String number = inputnumber + "";
        // As odd places, we need to decrement by 2
        for (int i = getNumberOfDigits(inputnumber) - 1; i >= 0; i -= 2)
            summation += Integer.parseInt(number.charAt(i) + "");       
        return summation;
    // Return true if the digit  is a prefix for number
    public static boolean checkForPrefixMatching(long inputnumber, int digit)
        return getPrefixNumber(inputnumber, getNumberOfDigits(digit)) == digit;
    // Return the number of digits
    public static int getNumberOfDigits(long digit)
        String number = digit + "";
        return number.length();
    // By using substring functionality, we can 
    // return the first k number of digits from
    // number. If the number of digits in number
    // is less than k, return number.
    public static long getPrefixNumber(long inputnumber, int k)
        if (getNumberOfDigits(inputnumber) > k) {
            String num = inputnumber + "";
            return Long.parseLong(num.substring(0, k));
        return inputnumber;

Now let us go with JUNIT test cases. It covers a few valid test credit card numbers from “American Express, Diners Club, Master, Visa card, etc.,”


import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumingThat;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestCreditCardService {
    public void testForValidCreditCardNumbers() {
        // Example for American Express card
        assertEquals(true, CreditCardValidation.checkForValidity(378282246310005L));
        assertNotEquals(true, CreditCardValidation.checkForValidity(37828224631015L));
        // Example for American Express Corporate card
        assertEquals(true, CreditCardValidation.checkForValidity(378734493671000L));
        // Example for Discover card
        assertFalse(CreditCardValidation.checkForValidity(6011111111111128L),"Invalid Creditcard");
        String validationName = "creditCardValidation";
         // In a grouped assertion all assertions are executed, and any
        // failures will be reported together.
        // Example for Master card and Visa
        assertAll("creditCardValidation", () -> assertTrue(CreditCardValidation.checkForValidity(5105105105105100L)),
                () -> assertTrue(CreditCardValidation.checkForValidity(4111111111111111L)));
        // Let us comment for the first time
        // assertAll("creditCardValidationYieldingFalse", () -> assertTrue(CreditCardValidation.checkForValidity(378282246310005L)),
        //                 () -> assertTrue(CreditCardValidation.checkForValidity(378282246310005L)));
        /* The assumingThat() method executes the rest of the statements 
           if the assumption is valid. If the assumption is invalid, 
           this method does nothing. 
           Advantage : To log the information
       // Example for Visa card
       assumingThat("creditCardValidation".equals(validationName), () -> {
            System.out.println("Checking for creditcard validation!!!");
            assertEquals(true, CreditCardValidation.checkForValidity(4012888888881881L));
        /* with assumeFalse
        * If the boolean condition in assumeFalse becomes false 
        * then only the next set of test method is executed, 
        * else the test is skipped. 
        // Example for Paymentech (Processor specific card)
        // Example for American Express,Diners and Master card (May be 3 people at a home are having 3 different cards, 
        // we can check in this way, instead of checking single single
        assertArrayEquals(new long[]{378282246310005L,30569309025904L,5555555555554444L},new long[]{378282246310005L,30569309025904L,5555555555554444L});
        Assertions.assertThrows(IllegalArgumentException.class, () -> {

Explanation for assertAll:

Sometimes there is a necessity for providing positive results, and multiple conditions to be checked

 assertAll("creditCardValidation", () -> assertTrue(CreditCardValidation.checkForValidity(5105105105105100L)),
                () -> assertTrue(CreditCardValidation.checkForValidity(4111111111111111L)));

Here two separate assertTrue statements are written and both should be true i.e. given card should be validated as true and then only the whole condition is passed.


In the above code, let us uncomment the below code

assertAll("creditCardValidationYieldingFalse", () -> assertTrue(CreditCardValidation.checkForValidity(378282246310005L)),
               () -> assertTrue(CreditCardValidation.checkForValidity(379382246310005L)));

Among the two cards given, the first one is a valid card and the second is not valid. Hence the whole condition becomes false and we can see that from the result also


For doing grouped test results, assertAll is very much helpful.


There are situations to proceed with the execution of the test case. For that scenario, we can use 

// Example for Visa card
assumingThat("creditCardValidation".equals(validationName), () -> { // Only when the condition is valid
            System.out.println("Checking for creditcard validation!!!");// We can log the required information here
            assertEquals(true, CreditCardValidation.checkForValidity(4012888888881881L));

Ironically to test something, we can use 


/* with assumeFalse
  * If the boolean condition in assumeFalse becomes false then only the next set of test method is executed, 
  * else the test is skipped. 
// false here and hence next statement is proceeded
// Example for Paymentech (Processor specific card)


Instead of testing a single card, we can put everything in an array and we can check that.

// Example for American Express,Diners and Master card (May be 3 people at a home are having 3 different cards, we can check in this way, instead of checking single single
assertArrayEquals(new long[]{378282246310005L,30569309025904L,5555555555554444L},new long[]{378282246310005L,30569309025904L,5555555555554444L});

Thus JUnit helps a lot to get quality software. By writing efficient JUnits, surely the best software can be produced.

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!