JUNIT / NOTES</>↗JUnit13 Jul 2026
In JUnit tests, you usually compare objects with assertions, not with ==. The most common choices are: assertEquals(expected, actual) — compares objects using their equals() method. assertSame(expected, actual) — checks whether both references point to the same object. AssertJ’s assertThat(actual).isEqualTo(expected) — a more fluent alternative. Field-by-field assertions — useful when you only care about some […]
JUNIT / NOTES</>↗JUnit13 Jul 2026
You can use AssertJ with JUnit to write more readable, fluent assertions than standard JUnit assertions. 1. Add AssertJ Dependency If you use Maven: <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.26.3</version> <scope>test</scope> </dependency> If you use Gradle: testImplementation("org.assertj:assertj-core:3.26.3") 2. Use AssertJ in a JUnit Test Import assertThat statically: import org.junit.jupiter.api.Test; import static org.as...
JUNIT / NOTES</>↗JUnit13 Jul 2026
You can test repository-like classes without a real database by replacing the database dependency with a fake, mock, or in-memory implementation, depending on what you want to verify. 1. Use mocks for unit tests If your class depends on a repository interface, mock it and verify behavior without touching a database. Example with JUnit 5 […]
JUNIT / NOTES</>↗JUnit13 Jul 2026
Testing Service Classes with JUnit and Mockito Service classes are usually where your business logic lives. They often depend on repositories, clients, mappers, validators, or other services. When unit testing a service, the goal is usually: test the service logic itself mock external dependencies avoid starting the Spring container unless necessary verify returned values, exceptions, […]
JUNIT / NOTES</>↗JUnit13 Jul 2026
In JUnit tests, you usually don’t “mock” exceptions directly. Instead, you either: Assert that real code throws an exception, or Configure a mock dependency to throw an exception. 1. Assert that code throws an exception With JUnit 5, use assertThrows. import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class MyServiceTest { @Test void shouldThrowException() { […]
JUNIT / NOTES</>↗JUnit13 Jul 2026
To verify method calls with Mockito and JUnit, use Mockito’s verify() method. This lets you check whether a mocked dependency method was called, how many times it was called, and what arguments were passed. 1. Basic Example Suppose you have a service that depends on a repository. public interface UserRepository { void save(User user); } […]