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

JUnit Master Complete Guide With Index

unit testing j unit guide

Uploaded by

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

JUnit Master Complete Guide With Index

unit testing j unit guide

Uploaded by

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

JUnit Master Complete Guide

<b>Index</b> <b>Page</b>

1. Introduction to JUnit 2
2. Why JUnit? 3
3. Setting Up JUnit 4
4. Basic JUnit Test Example 5
5. JUnit Lifecycle Annotations 6
6. Assertions in Depth 7
7. Parameterized Tests 8
8. Nested Tests 9
9. Tags and Filtering 10
10. Assumptions 11
11. Test Suites 12
12. JUnit with Mockito 13
13. JUnit with Spring Boot 14
14. Advanced Features 15
15. Best Practices 16

1. Introduction to JUnit
JUnit is a popular Java framework for unit testing. JUnit 5, also called Jupiter, is the latest version
that provides modern features for writing robust tests. JUnit integrates well with build tools like
Maven and Gradle, and frameworks like Spring Boot.

2. Why JUnit?
• Ensures code correctness
• Enables automated regression testing
• Improves maintainability
• Works with CI/CD pipelines
• Reduces bugs in production

3. Setting Up JUnit
Add the following Maven dependency for JUnit 5:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
4. Basic JUnit Test Example
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {

Calculator calculator;

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

@Test
void testAdd() {
int result = calculator.add(5, 3);
assertEquals(8, result);
}

@Test
void testDivide() {
assertThrows(ArithmeticException.class, () -> calculator.divide(5, 0));
}

@AfterEach
void tearDown() {
calculator = null;
}
}

5. JUnit Lifecycle Annotations


@BeforeEach - Runs before every test
@AfterEach - Runs after every test
@BeforeAll - Runs once before all tests (static method)
@AfterAll - Runs once after all tests (static method)
@DisplayName - Adds a custom name for readability
@Disabled - Skips the test method

6. Assertions in Depth
assertEquals(expected, actual)
assertTrue(condition)
assertFalse(condition)
assertNotNull(object)
assertThrows(Exception.class, executable)
assertAll(() -> assertEquals(4, 2+2), () -> assertTrue(3 > 2))

7. Parameterized Tests
@ParameterizedTest
@ValueSource(strings = {"madam", "racecar", "level"})
void testPalindrome(String word) {
assertTrue(isPalindrome(word));
}

8. Nested Tests
@Nested
class MathTests {
@Test
void testAddition() {
assertEquals(4, 2 + 2);
}

@Test
void testSubtraction() {
assertEquals(0, 2 - 2);
}
}

9. Tags and Filtering


@Tag("fast") can be used to categorize tests. You can run tests by tags using Maven: mvn test -Dgroup

10. Assumptions
assumeTrue(condition) and assumeFalse(condition) allow skipping tests when certain
preconditions are not met.

11. Test Suites


@RunWith(JUnitPlatform.class)
@SelectPackages("com.example.tests")
class AllTestsSuite {
}

12. JUnit with Mockito


@ExtendWith(MockitoExtension.class)
class StudentServiceTest {

@Mock
StudentRepository repository;

@InjectMocks
StudentService service;

@Test
void shouldReturnStudentWhenRollNumberExists() {
Student student = new Student("R123", "John");
when(repository.findByRollNumber("R123")).thenReturn(student);

Student result = service.getStudentByRollNumber("R123");

assertEquals("R123", result.getRollNumber());
}
}

13. JUnit with Spring Boot


@SpringBootTest
class StudentServiceIntegrationTest {

@Autowired
StudentService studentService;

@Test
void testGetStudentByRollNumber() {
Student student = studentService.getStudentByRollNumber("R123");
assertNotNull(student);
}
}

14. Advanced Features


@RepeatedTest - Runs a test multiple times
@TestFactory - Generates dynamic tests at runtime
@ExtendWith - Adds custom extensions
TestInfo and TestReporter for runtime info

15. Best Practices


✔ Name tests clearly: shouldDoSomethingWhenCondition
✔ Use AAA pattern: Arrange, Act, Assert
✔ Keep tests independent and repeatable
✔ Avoid complex logic inside tests

You might also like