0% found this document useful (0 votes)
13 views4 pages

JUnit

JUnit is a Java testing framework primarily used for unit testing, with the latest version being JUnit 5 (Jupiter). It automates testing to catch bugs early, ensure code changes don't break existing features, and facilitate safe code refactoring. The document also covers JUnit annotations, common assertions, integration with Spring Boot, and best practices for writing tests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views4 pages

JUnit

JUnit is a Java testing framework primarily used for unit testing, with the latest version being JUnit 5 (Jupiter). It automates testing to catch bugs early, ensure code changes don't break existing features, and facilitate safe code refactoring. The document also covers JUnit annotations, common assertions, integration with Spring Boot, and best practices for writing tests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

JUnit

What is JUnit?

JUnit is a Java testing framework used to write unit tests for your code. It helps
ensure your application logic works as expected by automatically verifying small
units (typically methods or classes) of code.

JUnit = "Java Unit Testing"

Latest version used widely: JUnit 5 (a.k.a. Jupiter)

Why Unit Testing?

Catch bugs early during development.

Automate testing → faster development.

Ensure future code changes don’t break existing features (regression testing).

Help refactor code safely.

JUnit Versions
| Version | Name | Key Features |
| ------- | ------- | -------------------------------- |
| JUnit 4 | Older | Uses `@Test`, no `@BeforeEach` |
| JUnit 5 | Jupiter | Modular, extensible, modern APIs |

Use JUnit 5 with Spring Boot for best results.

Maven Dependency for JUnit 5

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>

Or with Spring Boot Starter:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Note: Spring Boot Starter Test includes JUnit, Mockito, Hamcrest, etc.

Basic JUnit 5 Annotations


| Annotation | Description |
| -------------- | ------------------------------------------ |
| `@Test` | Marks a method as a test |
| `@BeforeEach` | Runs before each test |
| `@AfterEach` | Runs after each test |
| `@BeforeAll` | Runs once before all tests (static method) |
| `@AfterAll` | Runs once after all tests (static method) |
| `@Disabled` | Skip/ignore the test |
| `@DisplayName` | Custom name for test method |
| `@Nested` | Group related tests into inner classes |

Basic Example

import org.junit.jupiter.api.*;

class CalculatorTest {

Calculator calculator;

@BeforeEach
void init() {
calculator = new Calculator();
}

@Test
@DisplayName("Test addition")
void testAdd() {
Assertions.assertEquals(10, calculator.add(5, 5));
}

@Test
void testDivideByZero() {
Assertions.assertThrows(ArithmeticException.class, () ->
calculator.divide(10, 0));
}
}

Common Assertions in JUnit


| Assertion Method | Description |
| ---------------------------------- | ----------------------------------- |
| `assertEquals(expected, actual)` | Checks if values are equal |
| `assertNotEquals()` | Checks if values are not equal |
| `assertTrue(condition)` | Checks if condition is true |
| `assertFalse(condition)` | Checks if condition is false |
| `assertThrows()` | Asserts that an exception is thrown |
| `assertNull()` / `assertNotNull()` | Check for null values |

Spring Boot + JUnit Test


Example: Testing a Service

@SpringBootTest
class UserServiceTest {

@Autowired
private UserService userService;
@MockBean
private UserRepository userRepo;

@Test
void testGetUserById() {
User mockUser = new User(1L, "Smruti");
Mockito.when(userRepo.findById(1L)).thenReturn(Optional.of(mockUser));

User result = userService.getUserById(1L);


Assertions.assertEquals("Smruti", result.getName());
}
}

Breakdown:
@SpringBootTest: Loads the Spring context

@Autowired: Inject real beans

@MockBean: Replace real bean with Mockito mock

Mockito with JUnit


Use Mockito to mock dependencies.

@ExtendWith(MockitoExtension.class)
class AuthServiceTest {

@Mock
private UserRepository userRepo;

@InjectMocks
private AuthService authService;

@Test
void testRegisterUser() {
User user = new User("test", "[email protected]");
Mockito.when(userRepo.save(user)).thenReturn(user);

User result = authService.register(user);


Assertions.assertEquals("test", result.getName());
}
}

Best Practices
Name test methods clearly: shouldRegisterUserSuccessfully()

Keep tests fast, isolated, and repeatable

Use TestContainers for DB tests

Separate unit tests (fast) from integration tests (real DB/services)

Advanced: Parameterized Tests


@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testIsPositive(int number) {
Assertions.assertTrue(number > 0);
}

Folder Structure (Maven/Gradle)

src/
├── main/
│ └── java/ # Application code
└── test/
└── java/ # Unit tests

Types of Testing

| Type | Tool | Scope |


| ---------------- | -------------------- | ------------------- |
| Unit Testing | JUnit + Mockito | One class/method |
| Integration Test | SpringBootTest | Multiple components |
| API Test | RestAssured, Postman | Full API endpoints |
| End-to-End Test | Selenium, Cypress | Full UI + Backend |

You might also like