Write a JUnit 5 test by calling the code you want to check and asserting its result. Add Mockito only when a collaborator needs controlled behavior or when an important interaction is part of the contract. The example below uses JUnit Jupiter and Mockito’s Jupiter extension to test a small payment service.
What JUnit 5 and Mockito do
JUnit 5 is made up of the JUnit Platform, JUnit Jupiter, and JUnit Vintage. Jupiter is the programming and extension model used to write contemporary JUnit tests; the Platform provides the foundation that runs test engines. JUnit 5 User Guide
Mockito creates test doubles (mocks), lets you define their responses, and can check selected interactions. They solve different problems: JUnit structures and runs the test, while Mockito controls or observes a collaborator when doing so helps specify the behavior under test.
Set up the project dependencies
Add JUnit Jupiter and Mockito to the test scope using your build tool. If you use Mockito’s Jupiter extension, include the mockito-junit-jupiter artifact as well as the matching Mockito core version. The exact dependency versions and Java compatibility depend on your project; check the current release metadata and compatibility requirements before choosing them. Do not assume a version listed in an older API page is the right version for a new project.
Recommended Free Tools
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
For Maven, declare the relevant artifacts with test scope in your project’s dependency section; for Gradle, use the equivalent test dependencies. Configure the build to run JUnit Platform tests if your build setup requires it. The examples below assume those dependencies are already available to the test source set.
Write a basic JUnit Jupiter test
A test method marked with @Test calls the unit under test and checks an outcome with an assertion. Start with a real object when its behavior is deterministic and simple.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class TaxCalculator {
int addTax(int price, int tax) {
return price + tax;
}
}
class TaxCalculatorTest {
@Test
void addsTaxToPrice() {
TaxCalculator calculator = new TaxCalculator();
int total = calculator.addTax(100, 8);
assertEquals(108, total);
}
}
The test follows arrange, act, assert: create the object and inputs, call the method, then compare the actual value with the expected value. A test should make its expected behavior apparent without requiring readers to infer it from elaborate setup.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Use lifecycle and parameterized tests when they help
Use @BeforeEach for setup that genuinely belongs before every test in a class. Avoid moving a single obvious line into shared setup merely to reduce line count; local setup can make an individual test easier to read.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Use @ParameterizedTest when the same behavior should be checked against several inputs. Pair it with an appropriate argument source from the JUnit guide, rather than duplicating nearly identical test methods. JUnit 5 User Guide
Decide when a dependency should be mocked
Mock a collaborator when controlling its response makes the unit’s behavior predictable, isolates an external boundary, or lets the test verify a meaningful interaction. A payment gateway is a reasonable example: the service should respond correctly to an approved or declined charge without making a real payment.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Prefer real values and simple real objects for data and deterministic logic. Do not mock a dependency just because it is injected, and avoid mocking ordinary collection implementations in production tests. Mockito’s documentation covers mocks, stubbing, verification, and these cautions. Mockito API documentation
Connect Mockito to JUnit 5 with MockitoExtension
Register MockitoExtension with Jupiter’s @ExtendWith. The extension initializes annotated mocks and handles strict stubbings. Ensure the extension artifact matches the Mockito core version selected for the project; the surfaced extension API documentation is for version 4.11.0 and should not be treated as a universal dependency recommendation. MockitoExtension API · Jupiter ExtendWith API
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
record ChargeRequest(String accountId, int cents) {}
record ChargeResult(boolean approved) {}
interface PaymentGateway {
ChargeResult charge(ChargeRequest request);
}
class PaymentService {
private final PaymentGateway gateway;
PaymentService(PaymentGateway gateway) {
this.gateway = gateway;
}
boolean pay(ChargeRequest request) {
return gateway.charge(request).approved();
}
}
@ExtendWith(MockitoExtension.class)
class PaymentServiceTest {
@Mock
PaymentGateway gateway;
@Test
void returnsWhetherTheGatewayApprovedTheCharge() {
ChargeRequest request = new ChargeRequest("acct-7", 2500);
when(gateway.charge(request)).thenReturn(new ChargeResult(true));
PaymentService service = new PaymentService(gateway);
boolean paid = service.pay(request);
assertEquals(true, paid);
verify(gateway).charge(request);
}
}
This is a compact illustrative example; it has not been executed here. It uses Java records, so use a Java release that supports records, or replace them with ordinary classes if your project targets an earlier release. The test’s package and source-file layout should follow your project conventions.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Stub behavior and verify only meaningful interactions
Mockito’s common stubbing form is when(mock.method()).thenReturn(value). In the example, the gateway returns an approved result for the exact request, allowing the service’s response to be tested without invoking a real payment system.
Assert the result or other observable behavior first. Add verify(mock).method(...) when the call itself is important—for example, when the service must submit the correct request to its gateway. Routine verifyNoMoreInteractions() checks can overspecify implementation details and make harmless refactoring break tests. Mockito API documentation
Use argument matchers consistently
If you use Mockito argument matchers for an invocation, use matchers for all arguments in that invocation. Do not mix a matcher such as any() with a raw argument in the same call. Check the API for the matcher methods and behavior available in your selected Mockito version.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesBest Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Handle void methods and spies deliberately
For void methods, or when stubbing a spy would cause when(...) to evaluate the real method, consult Mockito’s doReturn, doThrow, and related APIs instead of applying the ordinary stubbing form mechanically. A spy calls real behavior unless that behavior is changed; use one only when that partial-real-object behavior is actually needed. Mockito API documentation
Choose between a real object and a mock
| Choice | Use it when | Watch for |
|---|---|---|
| Real object | The behavior is deterministic, simple, and inexpensive to construct. | Do not bring in unnecessary external effects merely to avoid a mock. |
| Mock | You need a controlled collaborator response or an important interaction is part of the behavior being specified. | Excessive stubbing and exhaustive interaction checks can couple a test to implementation details. |
Troubleshoot common test problems
- JUnit does not discover the test: confirm the method is annotated with Jupiter’s
@Test, the test source is in the build’s test source set, and the build is configured to run the JUnit Platform where required. @Mockis not initialized: registerMockitoExtensionwith@ExtendWithand include the Jupiter integration artifact. Do not mix an extension artifact from a different Mockito line without checking compatibility.- A stub appears unused or strict stubbing fails: check that the unit calls the same mock method with arguments matching the stubbing, and remove stubs the test no longer needs. The extension applies strict stubbing, which helps expose unnecessary or mismatched stubs.
- A mock returns an unexpected value: confirm the invocation matches the stubbed method and arguments. Unstubbed mock behavior is Mockito-version-sensitive; consult the selected version’s documentation rather than relying on assumptions about defaults.
- Matcher usage fails: when any argument uses a matcher, use matchers for every argument in that invocation.
- A spy executes code while stubbing:
when(spy.method())can call the real method. Use the appropriatedoReturnordoThrowform when needed, and reconsider whether a mock or a real object is clearer. - Dependency resolution or compilation fails: verify that the Mockito core and Jupiter integration versions align, that the chosen releases support the project’s Java baseline, and that test dependencies are declared in the correct scope.
Or skip the browser setup
This Java test tutorial does not require a browser screenshot service. For a separate task where a test or agent needs a page capture, ScreenshotNeo is a website screenshot API and MCP server. One GET request can return an image or PDF; for example, using the API’s documented cURL pattern:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for request options. It accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses report page verdict and billing headers. Its MCP server provides screenshot, page-info, and PDF tools for AI agents. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots.
Sign up for 1,000 free screenshots a month, with no card required.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Frequently Asked Questions
Can I use JUnit 5 without Mockito?
Yes. JUnit Jupiter assertions are sufficient when the code under test has no collaborator that needs controlled behavior or interaction verification.
Does Mockito replace JUnit?
No. Mockito supplies test doubles and mocking operations; JUnit Jupiter provides the test and extension model.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

