Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java JUnit Unit Testing Framework

Java JUnit Unit Testing Framework

Common Java Libraries Common Java Libraries


JUnit is one of the most popular unit testing frameworks in the Java programming language, used to write and run repeatable automated tests.

JUnit was created by Kent Beck and Erich Gamma and is a member of the xUnit family. Unit testing refers to the process of inspecting and verifying the smallest testable parts of software (usually methods or classes).

The main features of JUnit include:


Why Do We Need Unit Testing?

Unit testing is an indispensable part of modern software development; it brings the following benefits:

  1. Find Problems Early: Discover and fix errors during development
  2. Improve Code Quality: Forces developers to write more modular, testable code
  3. Documentation Effect: Test cases themselves are the best documentation of code behavior
  4. Refactoring Safety Net: Ensures that modifying code does not break existing functionality
  5. Reduce Debugging Time: Quickly locate where problems are

Using JUnit in a Project

For JUnit 5:



    org.junit.jupiter
    junit-jupiter
    5.8.2
    test

For JUnit 4:



    junit
    junit
    4.13.2
    test


JUnit 5 Basics

JUnit 5 is the latest version and consists of three main modules:

Basic Annotations

Legacy annotations:

Example

import

org.junit.*

;

public

class

CalculatorTest

{

   

    @BeforeClass

   

public

static

void

setUpBeforeClass

(

)

{

       

System

.

out

.

println

(

"Before all tests"

)

;

   

}

   

    @Before

   

public

void

setUp

(

)

{

       

System

.

out

.

println

(

"Before each test"

)

;

   

}

   

    @Test

   

public

void

testAddition

(

)

{

        Calculator calculator

=

new

Calculator

(

)

;

       

int

result

=

calculator.

add

(

2

,

3

)

;

       

Assert

.

assertEquals

(

5

, result

)

;

   

}

   

    @Test

    @Ignore

(

"Not implemented yet"

)

   

public

void

testSubtraction

(

)

{

       

// Test code

   

}

   

    @After

   

public

void

tearDown

(

)

{

       

System

.

out

.

println

(

"After each test"

)

;

   

}

   

    @AfterClass

   

public

static

void

tearDownAfterClass

(

)

{

       

System

.

out

.

println

(

"After all tests"

)

;

   

}

}

JUnit 5 is a new-generation version; the new annotations are as follows:

Example

import

org.junit.jupiter.api.*

;

@Test

void

testMethod

(

)

{

   

// Test code

}

@BeforeEach

void

setUp

(

)

{

   

// Executed before each test method runs

}

@AfterEach

void

tearDown

(

)

{

   

// Executed after each test method runs

}

@BeforeAll

static

void

initAll

(

)

{

   

// Executed once before all test methods run

}

@AfterAll

static

void

tearDownAll

(

)

{

   

// Executed once after all test methods run

}

Common Assertion Methods

JUnit provides a rich set of assertion methods to verify test results:

Example

import

static

org.

junit

.

jupiter

.

api

.

Assertions

.

*;

@Test

void

testAssertions

(

)

{

   

// Equality assertion

    assertEquals

(

expected, actual

)

;

   

   

// True assertion

    assertTrue

(

condition

)

;

   

   

// Null assertion

    assertNull

(

object

)

;

   

   

// Exception assertion

    assertThrows

(

ExpectedException.

class

,

(

)

->

{

       

// Code that throws an exception

   

}

)

;

   

   

// Timeout assertion

    assertTimeout

(

Duration.

ofMillis

(

100

)

,

(

)

->

{

       

// Code that should complete within the specified time

   

}

)

;

}


Writing Your First JUnit Test

Let us learn how to write a JUnit test through a simple example.

1. Create the class under test

Example

public

class

Calculator

{

   

public

int

add

(

int

a,

int

b

)

{

       

return

a

b

;

   

}

   

   

public

int

divide

(

int

a,

int

b

)

{

       

if

(

b

==

0

)

{

           

throw

new

ArithmeticException

(

"Divisor cannot be zero"

)

;

       

}

       

return

a

/

b

;

   

}

}

2. Create the test class

Example

import

org.junit.jupiter.api.*

;

import

static

org.

junit

.

jupiter

.

api

.

Assertions

.

*;

class

CalculatorTest

{

   

private

Calculator calculator

;

   

    @BeforeEach

   

void

setUp

(

)

{

        calculator

=

new

Calculator

(

)

;

   

}

   

    @Test

   

void

testAdd

(

)

{

        assertEquals

(

5

, calculator.

add

(

2

,

3

)

)

;

   

}

   

    @Test

   

void

testDivide

(

)

{

        assertEquals

(

2

, calculator.

divide

(

6

,

3

)

)

;

   

}

   

    @Test

   

void

testDivideByZero

(

)

{

        assertThrows

(

ArithmeticException

.

class

,

(

)

->

{

            calculator.

divide

(

1

,

0

)

;

       

}

)

;

   

}

}


JUnit Advanced Features

Parameterized Tests

JUnit 5 provides the @ParameterizedTest annotation, which allows running the same test multiple times with different parameters:

Example

@ParameterizedTest

@ValueSource

(

ints

=

{

1

,

2

,

3

}

)

void

testWithValueSource

(

int

argument

)

{

    assertTrue

(

argument

0

&&

argument

<
4
)

;

}

Test Lifecycle

Understanding the JUnit test lifecycle is important for writing effective tests:

  1. @BeforeAll method executes (once only)
  2. For each test method:
  3. Create test class instance
  4. @BeforeEach method executes
  5. Test method executes
  6. @AfterEach method executes
  7. - Create test class instance - `@BeforeEach` method executes - Test method executes - `@AfterEach` method executes
    1. @AfterAll method executes (once only)

    Test Suites

    You can use the @Suite annotation combines multiple test classes to run together:

    Example

    import

    org.junit.platform.suite.api.SelectClasses

    ;

    import

    org.junit.platform.suite.api.Suite

    ;

    @Suite

    @SelectClasses

    (

    {

    CalculatorTest.

    class

    , AnotherTest.

    class

    }

    )

    public

    class

    TestSuite

    {

    }


    Best Practices

    1. Test Naming: Test method names should clearly express their intent, such as shouldReturnTrueWhenInputIsValid()
    2. Single Responsibility: Each test method tests only one feature point
    3. Independent Tests: There should be no dependencies between tests
    4. Fast Feedback: Keep tests running fast
    5. Test Coverage: Pursue reasonable coverage, but do not blindly pursue 100%
    6. Test Data: Use meaningful test data
    7. Avoid Testing Implementation Details: Test behavior rather than implementation

    Frequently Asked Questions

    What is the difference between JUnit 4 and JUnit 5?

    The main differences include:

    How to Run JUnit Tests?

    You can run JUnit tests in the following ways:

    1. Right-click the test class or method in the IDE and select "Run"
    2. Using Maven:mvn test
    3. Using Gradle:gradle test
    4. Using the JUnit Console Launcher

    How to Test Private Methods?

    It is generally not recommended to test private methods directly; instead, indirectly test them through public methods. If you must test private methods, consider:

    1. Using reflection
    2. Change the method to package-private (no modifier) and create a test class with the same package structure under the test directory
    3. Refactor the code to extract the private method's logic into a separate class

    Summary

    JUnit is an essential testing tool for Java developers; mastering it can significantly improve code quality and development efficiency. Start with simple unit tests and gradually learn more advanced features, such as parameterized tests and test suites. Remember, good tests should be valued as much as production code, and keeping test code clean and maintainable is equally important.

    Common Java Libraries Common Java Libraries