0% found this document useful (0 votes)
21 views

JUnit_Documentation

JUnit is an open-source testing framework for Java, primarily used for unit testing, enabling developers to write automated test cases. It operates through a structured flow involving initialization, execution, validation, and cleanup, with various annotations to define test behavior. The document also details the project structure, dependencies for JUnit 5, and provides examples of test classes and major annotations used in JUnit 5.

Uploaded by

navneetgupta2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

JUnit_Documentation

JUnit is an open-source testing framework for Java, primarily used for unit testing, enabling developers to write automated test cases. It operates through a structured flow involving initialization, execution, validation, and cleanup, with various annotations to define test behavior. The document also details the project structure, dependencies for JUnit 5, and provides examples of test classes and major annotations used in JUnit 5.

Uploaded by

navneetgupta2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Unit Testing with JUnit

Introduction to JUnit
JUnit is a popular open-source testing framework for Java that is primarily used for
unit testing. It allows developers to write repeatable and automated test cases to
ensure the correctness of their code. JUnit plays a crucial role in Test-Driven
Development (TDD) by enabling incremental code development through frequent
testing.

How JUnit Works:


- JUnit tests are written as Java classes with special annotations to define the test
structure.
- Each method annotated with @Test is treated as a test case.
- JUnit runs test methods in isolation to ensure that each test executes independently.
- Assertions are used to verify that the expected and actual results match.
- The framework provides lifecycle methods (@BeforeAll, @BeforeEach, @AfterAll,
@AfterEach) to handle pre- and post-test execution logic.

Flow and Architecture:


1. Initialization:
- @BeforeAll – Runs once before all tests (e.g., setting up resources).
- @BeforeEach – Runs before each test (e.g., initializing data).
2. Execution:
- Test methods marked with @Test are executed.
3. Validation:
- Assertions validate whether the test passes or fails.
4. Cleanup:
- @AfterEach – Runs after each test
(e.g., clearing data).
- @AfterAll – Runs once after all tests
(e.g., closing resources).
JUnit Architecture:
- JUnit API – Provides core classes and interfaces for writing tests.
- JUnit Engine – Executes test cases and reports results.
- Test Runner – Responsible for discovering and running test methods.
- Assertions – Utility methods that validate test results.

Project Structure

pom.xml Configuration
The pom.xml file manages dependencies and build configurations for the project.
 This is a JUnit 4 dependency. It has been commented out, meaning it is not being
used in the current configuration. If enabled, it would provide JUnit 4 support for
running tests. The version is 4.12, and it is scoped to test, indicating it would only be
used during testing and not included in the final build.
 JUnit 5 dependencies: These dependencies are for JUnit 5, which is the next
version of JUnit and is recommended for new projects. It consists of several modules,
each serving different purposes. Here, three dependencies are included:
o JUnit Jupiter API: This is the core API for writing tests in JUnit 5, which includes
annotations like @Test, @BeforeEach, @AfterEach, etc. The version 5.11.4 is
specified, and the scope is test to indicate it is used only in testing.
o JUnit Jupiter Engine: This dependency includes the engine required to actually
run the JUnit 5 tests. The junit-jupiter-engine runs tests written with the JUnit Jupiter
API. This is also scoped to test, meaning it's only used during the testing phase.
o JUnit Jupiter Parameters:
o This module provides support for parameterized tests, which allow you to run
the same test with different sets of input data. It is also scoped to test to
ensure it’s available only during testing.
o Summary:
 The commented-out JUnit 4 dependency is unused.
 The three active dependencies are for JUnit 5:
 junit-jupiter-api: Used for writing tests.
 junit-jupiter-engine: Required for running tests.
 junit-jupiter-params: For parameterized tests.

Source Code Breakdown


1. CalculatorService.java
package com.myapp.Services;
public class CalculatorService {

public static int addTwoNumbers(int a,int b){


return a+b;
}
public static int productTwoNumbers(int a,int b){
return a*b;
}
public static double divideTwoNumbers(int a,int b){
return a/b;
}
public static int sumAnyNumbers(int... numbers) {
int s=0;
for(int n:numbers){
s+=n;
}
return s;
}
}

The CalculatorService class provides methods for basic arithmetic operations:


addition, multiplication, division, and summing any number of integers. It uses
variable arguments (int... numbers) in sumAnyNumbers to calculate the sum of a
variable number of integers.

2. CalculatorServiceTestJunit5.java
package com.myapp.Services;

import org.junit.jupiter.api.*;

import java.lang.annotation.Target;

public class CalculatorServiceTestJunit5 {

@BeforeAll // Runs once before all test cases


public static void beforeClass() {
System.out.println("Before All Class");
}

@AfterAll // Runs once after all test cases


public static void afterClass() {
System.out.println("After All Class");
}

@BeforeEach
public void beforeEach() {
System.out.println("Before Each Case");
}

@AfterEach
public void afterEach() {
System.out.println("After Each Case");
}

@Test
public void testAddTwoNumbers() {
int result = CalculatorService.addTwoNumbers(1, 2);
int expected = 3;
Assertions.assertEquals(expected, result, "Test failed!");
System.out.println("First test case");
}

// @Disabled
@Test
public void testAddAnyNumberTest() {
int result = CalculatorService.sumAnyNumbers(1, 2, 3, 4, 5);
int expected = 15;
Assertions.assertEquals(expected, result, "Test failed!");
System.out.println("Second test case");
}

// @Tag
// @Nested
// @TestFactory

}
The CalculatorServiceTestJunit5 class is a JUnit 5 test class that tests methods of the
CalculatorService class. Here's a brief explanation:

 Annotations:

o @BeforeAll: Runs once before all test methods, typically for setup.

o @AfterAll: Runs once after all test methods, typically for cleanup.

o @BeforeEach: Runs before each test method, often used for preparing
the test environment.

o @AfterEach: Runs after each test method, typically for cleanup after
each test.

 Test Methods:

o testAddTwoNumbers(): Tests the addTwoNumbers() method of


CalculatorService by checking if adding 1 and 2 equals 3.

o testAddAnyNumberTest(): Tests the sumAnyNumbers() method of


CalculatorService by checking if summing the numbers 1, 2, 3, 4, 5
equals 15. This test is commented out with @Disabled, so it will not run.

The class uses JUnit 5 features like @Test, Assertions.assertEquals(), and lifecycle
annotations (@BeforeAll, @AfterAll, etc.) to structure and validate test cases.
Majority annotations used
Here’s an explanation of the major JUnit 5 annotations without examples:

1. @Test

 Purpose: Marks a method as a test method.

2. @BeforeAll

 Purpose: Runs once before all test methods in the test class. The method must
be static.

3. @AfterAll

 Purpose: Runs once after all test methods in the test class. The method must
be static.

4. @BeforeEach

 Purpose: Runs before each test method.

5. @AfterEach

 Purpose: Runs after each test method.

6. @Disabled

 Purpose: Disables a test method or class, so it will not be executed.

7. @Tag

 Purpose: Tags a test with a label to categorize or group tests.

8. @Nested

 Purpose: Defines a nested class to logically group tests.

9. @ParameterizedTest

 Purpose: Marks a method as a parameterized test, allowing the method to run


with different sets of input values.

10. @ValueSource

 Purpose: Provides simple parameterized input for a test method annotated


with @ParameterizedTest.

11. @TestFactory

 Purpose: Marks a method that generates dynamic tests at runtime.

12. @TestInstance
 Purpose: Configures how instances of the test class are created, either
PER_METHOD or PER_CLASS.

13. @Timeout

 Purpose: Specifies the maximum duration for a test to run. If the test takes
longer, it fails.

14. @ExpectedException (Deprecated)

 Purpose: Previously used in JUnit 4 to specify the expected exception in a test.


Replaced by assertThrows in JUnit 5.

You might also like