JUNIT / CATATAN</>↗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 / CATATAN</>↗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); } […]
JUNIT / CATATAN</>↗JUnit13 Jul 2026
To use @Mock and @InjectMocks with JUnit, you typically use them with Mockito. @Mock creates a fake/mock dependency. @InjectMocks creates the class under test and injects the mocks into it. With JUnit 5, you enable Mockito using @ExtendWith(MockitoExtension.class). 1. Add Mockito dependencies Maven <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.11.4</version> <scope>test</scope> </dependency> <dependency> <gr...
JUNIT / CATATAN</>↗JUnit13 Jul 2026
To mock dependencies in unit tests, you usually use a mocking framework such as Mockito. Mocking lets you test one class in isolation without running the real logic of its collaborators. Basic Mockito Example Suppose you have a service that depends on another class: @Service public class MyService { private final MyDependency dependency; public MyService(MyDependency […]
JUNIT / CATATAN</>↗JUnit13 Jul 2026
To use Mockito with JUnit, you add Mockito to your test dependencies, enable Mockito in your JUnit test class, then create mocks and define their behavior. Below is a simple JUnit 5 + Mockito example. 1. Add Dependencies Maven <dependencies> <!– JUnit 5 –> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.11.4</version> <scope>test</scope> </dependency> <!– Mockito Core –> <dependency> […]
JUNIT / CATATAN</>↗JUnit13 Jul 2026
Java records are compact classes designed to hold immutable data. Because records automatically provide a constructor, accessor methods, equals(), hashCode(), and toString(), testing them is usually simpler than testing ordinary classes. In most cases, you do not need to test Java’s generated record behavior directly. Instead, test: custom validation in the compact constructor custom methods […]