Java Junit Lib
[ Java Common Libraries](#)
* * *
JUnit is one of the most popular unit testing frameworks in the Java programming language, used for writing and running 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 checking and verifying the smallest testable part of software (usually a method or class).
The main features of JUnit include:
* Provides annotations to identify test methods
* Provides assertions to verify expected results
* Supports test suites
* Provides test runners
* * *
## Why Do We Need Unit Testing?
Unit testing is an indispensable part of modern software development, bringing the following benefits:
1. **Early Problem Detection**: Find and fix errors during the development process
2. **Improved Code Quality**: Forces developers to write more modular, testable code
3. **Documentation**: Test cases themselves are the best documentation of code behavior
4. **Refactoring Safety Net**: Ensures that code changes don't break existing functionality
5. **Reduced Debugging Time**: Quickly locates problems
### Using JUnit in Your 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:
* JUnit Platform (the foundation for test execution)
* JUnit Jupiter (the new programming and extension model)
* JUnit Vintage (supports running JUnit 3 and 4 tests)
### Basic Annotations
Legacy annotations:
* `@Test`: Marks a method as a test method
* `@Before`: Executes before each test method
* `@After`: Executes after each test method
* `@BeforeClass`: Executes before all tests (static method)
* `@AfterClass`: Executes after all tests (static method)
* `@Ignore`: Ignores a test method
## 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 the new generation version, with new annotations as follows:
* `@BeforeEach` replaces `@Before`
* `@AfterEach` replaces `@After`
* `@BeforeAll` replaces `@BeforeClass`
* `@AfterAll` replaces `@AfterClass`
* `@Disabled` replaces `@Ignore`
## Example
import org.junit.jupiter.api.*;
@Test
void testMethod(){
// Test code
}
@BeforeEach
void setUp(){
// Executes before each test method
}
@AfterEach
void tearDown(){
// Executes after each test method
}
@BeforeAll
static void initAll(){
// Executes once before all test methods
}
@AfterAll
static void tearDownAll(){
// Executes once after all test methods
}
### Common Assertion Methods
JUnit provides rich assertion methods to verify test results:
* `assertEquals(expected, actual)`
* `assertTrue(condition)`
* `assertFalse(condition)`
* `assertNull(object)`
* `assertNotNull(object)`
* `assertSame(expected, actual)` (checks if it's the same object)
* `assertNotSame(unexpected, actual)`
* `assertArrayEquals(expectedArray, actualArray)`
## 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 specified time
});
}
* * *
## Writing Your First JUnit Test
Let's learn how to write JUnit tests 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, allowing the same test to be run 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:
* Create test class instance
* `@BeforeEach` method executes
* Test method executes
* `@AfterEach` method executes
3. `@AfterAll` method executes (once only)
### Test Suites
You can use the `@Suite` annotation to combine 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, e.g., `shouldReturnTrueWhenInputIsValid()`
2. **Single Responsibility**: Each test method should test only one feature point
3. **Independent Tests**: Tests should not have dependencies on each other
4. **Fast Feedback**: Keep tests running quickly
5. **Test Coverage**: Pursue reasonable coverage, but don't blindly pursue 100%
6. **Test Data**: Use meaningful test data
7. **Avoid Testing Implementation Details**: Test behavior, not implementation
* * *
## Frequently Asked Questions
### What's the Difference Between JUnit 4 and JUnit 5?
Main differences include:
* JUnit 5 requires Java 8 or higher
* Annotations moved from `org.junit` package to `org.junit.jupiter.api` package
* `@Before` and `@After` changed to `@BeforeEach` and `@AfterEach`
* `@BeforeClass` and `@AfterClass` changed to `@BeforeAll
YouTip