Table of contents
1.
Introduction
2.
Getting Started
2.1.
build.gradle
2.2.
Project Structure
2.3.
Example of Nested class Test
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Junit Nested Tests

Author Aman Thakur
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The article covers the detailed setup and execution of nested classes. A class is termed as a nested class if it is put inside another class and arranged in the hierarchical order. Before discussing the setup and execution. 
When do we need nested classes? There are situations when the test class can contain several complex tests logic which need to be tested in such cases nested classes are used.

How to implement nested classes? A non-specialist would answer that the complex and multiple test cases are broken so that each test could be smaller and modularized. The several tests can be grouped under a single test class in a nested fashion.

Getting Started

build.gradle


sourceCompatibility = 1.8


repositories {
   mavenCentral()
}


dependencies {
   testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter', version: '5.8.2'
}


test {
   useJUnitPlatform()
   testLogging {
       events "passed", "skipped", "failed"
   }
}
You can also try this code with Online Java Compiler
Run Code

Project Structure

Example of Nested class Test

Create Money

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;


public class Money {
   private final CurrencyUnit currency;
   private final BigDecimal amount;


   private Money(CurrencyUnit currency, BigDecimal amount) {
       this.currency = currency;
       this.amount = amount;
   }


   public static Money of(CurrencyUnit currency, Double amount) {
       return new Money(currency, new BigDecimal(amount).setScale(2, RoundingMode.HALF_UP));
   }


   public Money add(Money money) {
       if (!currency.equals(money.currency)) {
           throw new CurrencyMismatchException();
       }
       return new Money(currency, amount.add(money.amount));
   }


   public BigDecimal getAmount() {
       return amount;
   }


   @Override
   public boolean equals(Object o) {
       if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;
       Money money = (Money) o;
       return Objects.equals(currency, money.currency) && Objects.equals(amount, money.amount);
   }


   @Override
   public int hashCode() {
       return Objects.hash(currency, amount);
   }
}
You can also try this code with Online Java Compiler
Run Code

Create CurrencyUnit

public class CurrencyUnit {
   private final String unit;


   private CurrencyUnit(String unit) {
       this.unit = unit;
   }


   public static CurrencyUnit of(String unit) {
       return new CurrencyUnit(unit);
   }


   public String getUnit() {
       return unit;
   }
}
You can also try this code with Online Java Compiler
Run Code

Create CurrencyMismatchException 

public class CurrencyMismatchException extends RuntimeException {}
You can also try this code with Online Java Compiler
Run Code

Create MoneyTest

import org.junit.jupiter.api.*;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.*;


public class MoneyTest {
   @Nested
   @DisplayName("equality is based on values")
   class Equality {
       @Test
       @DisplayName("monies with same amounts are equal")
       void moniesWithSameAmountsAreEqual() {
           CurrencyUnit eur = CurrencyUnit.of("EUR");
           Money first = Money.of(eur, 3.99);
           Money second = Money.of(eur, 3.99);
           assertEquals(second, first);
       }


       @Test
       @DisplayName("monies with different amounts are not equal")
       void moniesWithDifferentAmountsAreNotEqual() {
           CurrencyUnit eur = CurrencyUnit.of("EUR");
           Money first = Money.of(eur, 3.99);
           Money second = Money.of(eur, 3.89);
           assertNotEquals(second, first);
       }


       @Test
       @DisplayName("monies with different currencies are not equal")
       void moniesWithDifferentCurrenciesAreNotEqual() {
           CurrencyUnit eur = CurrencyUnit.of("EUR");
           CurrencyUnit usd = CurrencyUnit.of("USD");
           Money first = Money.of(eur, 3.99);
           Money second = Money.of(usd, 3.99);
           assertNotEquals(second, first);
       }
   }


   @Nested
   @DisplayName("adding monetary amounts")
   class Addition {
       @Test
       @DisplayName("can add monies of same currency")
       void addMoneyWithSameCurrency() {
           CurrencyUnit eur = CurrencyUnit.of("EUR");
           Money money = Money.of(eur, 4.25);
           Money addend = Money.of(eur, 1.4);
           Money sum = money.add(addend);
           assertEquals(BigDecimal.valueOf(5.65), sum.getAmount());
       }


       @Test
       @DisplayName("cannot add monies of different currency")
       void addMoneyWithDifferentCurrency() {
           CurrencyUnit eur = CurrencyUnit.of("EUR");
           CurrencyUnit usd = CurrencyUnit.of("USD");
           Money money = Money.of(eur, 4.25);
           Money addend = Money.of(usd, 1.4);
           assertThrows(CurrencyMismatchException.class, () -> money.add(addend));
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

Now hit this button to test our application 

Output Window

FAQs

  1. What is a nested test?
    Junit 5 nested tests describe tests in a hierarchy and express the link between different sets of tests. You can have an inner class in a test class that is another test class using the @Nested annotation.
     
  2. What is @nested in JUnit?
    The @Nested annotation in JUnit Jupiter may be used to indicate that a nested class should be included in the test cases. Nested classes are not inspected for test methods when JUnit tests are run. We may use the @Nested annotation to indicate that they should be searched for test cases.
     
  3. Does JUnit run tests in parallel?
    In the junit-platform. properties file, set the enabled configuration value to true. According to the configuration, the JUnit Jupiter engine will run tests in parallel using defined synchronization mechanisms when the parallel test execution attribute is set to true.
     
  4. Can you convert JUnit test scripts to testing how?
    Simply add the JUnit library to the TestNG classpath so that it can discover and utilise JUnit classes, switch your test runner from JUnit to TestNG in Ant, then run TestNG in "mixed" mode. This way, you may start utilising TestNG with all of your tests in the same project, even in the same package.

Key Takeaways

The article discussed about @Nested annotation in JUnit Jupiter may be used to indicate that a nested class should be included in the test cases. Nested classes are not inspected for test methods when JUnit tests are run. We may use the @Nested annotation to indicate that they should be searched for test cases.

Check out JUnit Interview Questions here.

Hope you like this blog. Hence never stop your journey of learning.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Learning!

Live masterclass