The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →For a new Java unit test, start with JUnit Jupiter: write a focused method annotated with @Test, exercise one behavior, and assert an observable result. Add Mockito only when a collaborator needs to be isolated. Run the test through the project’s existing IDE or Maven or Gradle configuration, and make sure that configuration includes the JUnit engine needed to discover it.
How do I write unit tests in Java?
A unit test checks a small piece of behavior without needing to launch the whole application. Choose the smallest useful boundary: a method or class whose input and output, or other observable effect, can be checked predictably. Prefer a real lightweight collaborator when it is simple to construct; introduce a mock when an external or complex collaborator would make the test slow, unpredictable, or irrelevant to the behavior under test.
JUnit 5 is a collection of components rather than one single library. The JUnit Platform launches test engines, Jupiter provides the programming model and extension support for new tests, and Vintage runs JUnit 3 and JUnit 4 tests on the Platform. The examples below use Jupiter. The official JUnit 5.12.0 guide specifies Java 8 or higher at runtime; check the compatibility requirements for the exact JUnit version and Java runtime your project uses.
A small test: setup, action, assertion
Suppose a price calculator applies a discount and rejects invalid inputs:
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitches#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.
public final class PriceCalculator {
public int discountedPrice(int price, int discountPercent) {
if (price < 0) {
throw new IllegalArgumentException("price must not be negative");
}
if (discountPercent < 0 || discountPercent > 100) {
throw new IllegalArgumentException("discount must be from 0 to 100");
}
return price - (price * discountPercent / 100);
}
}
A Jupiter test can arrange the object, call the behavior, and assert the result:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PriceCalculatorTest {
@Test
void appliesDiscountToPrice() {
PriceCalculator calculator = new PriceCalculator();
int result = calculator.discountedPrice(100, 20);
assertEquals(80, result);
}
}
The test name describes the behavior rather than the implementation. The assertion compares the expected value with the actual result, making a failure useful to read. Jupiter includes assertions, assumptions, exception handling, tags, lifecycle controls, and parameterized tests; a third-party assertion library is not required for a first test.
Test specified failure behavior
When an exception is part of the method’s contract, assert that exception directly. This checks both that failure occurs and that it occurs for the intended call:
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.
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void rejectsNegativePrice() {
PriceCalculator calculator = new PriceCalculator();
IllegalArgumentException error = assertThrows(
IllegalArgumentException.class,
() -> calculator.discountedPrice(-1, 10)
);
assertEquals("price must not be negative", error.getMessage());
}
Only assert details such as an exception message when that detail is meaningful and stable for callers. Avoid broad tests that pass merely because some unrelated line throws an exception.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Exercise representative inputs with a parameterized test
If the same rule should hold across several inputs, a parameterized test keeps the assertion in one place while making the cases visible:
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ParameterizedTest
@CsvSource({
"100, 20, 80",
"50, 10, 45",
"80, 0, 80",
"80, 100, 0"
})
void calculatesDiscount(int price, int discountPercent, int expected) {
PriceCalculator calculator = new PriceCalculator();
assertEquals(expected, calculator.discountedPrice(price, discountPercent));
}
Include cases that represent meaningful boundaries as well as ordinary values. Parameterized tests require the corresponding Jupiter parameterized-test support to be present in the project’s version-matched dependencies.
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.
How should test setup and lifecycle work?
By default, Jupiter creates a fresh test-class instance for each test method. This reduces the risk that mutable instance fields changed by one test will leak into another. Tests should still avoid order dependencies: each test needs to establish its own relevant state rather than relying on a previous test having run.
Use lifecycle methods for genuinely shared setup
@BeforeEach runs before each test method; @AfterEach runs after each one. Use them when setup or cleanup is common and clearer than repeating it. For example, a test class can create a fresh calculator in @BeforeEach if many tests use it. Do not move important test-specific conditions into hidden setup: a reader should be able to see what each test is checking.
Mutable state, shared files, clocks, databases, or network services can undermine independence even when each test gets a new class instance. Give each test controlled inputs and clean up resources it creates. Use nested tests when grouping cases by context makes the behavior easier to navigate; do not add nesting just to create more headings.
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
How do I use JUnit 5 with Mockito?
Mockito is optional. It is useful when a class delegates to a collaborator and the test needs to control that collaborator’s response. The JUnit Jupiter extension integrates Mockito with Jupiter. In the following example, the service behavior depends on a repository result, so the mock isolates that boundary:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class GreetingServiceTest {
@Mock
GreetingRepository repository;
@Test
void returnsGreetingFromRepository() {
when(repository.findGreeting("en")).thenReturn("Hello");
GreetingService service = new GreetingService(repository);
String result = service.greetingFor("en");
assertEquals("Hello", result);
}
}
This assumes the application has a GreetingRepository interface with findGreeting(String) and a GreetingService constructor and method matching the example. Mockito’s Jupiter extension and the Mockito API version must be available to the test runtime. The Mockito 5.17.0 API documents the extension and strict-stubbing facilities; follow the guidance for the version your project actually uses.
Mock behavior, not every implementation step
The example stubs a response and asserts the service’s result. Verifying an interaction is appropriate when that interaction itself is part of the contract—for example, a message must be sent exactly once. Otherwise, assertions about meaningful outputs or state are generally less brittle than checking every call made internally. Mockito’s default style is described as loose, with strictness features intended to improve debugging; avoid unnecessary stubs and keep the test’s intent clear.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteBest 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.
How do I run Java unit tests?
Use the route the project already supports so local runs and continuous integration discover the same tests. The JUnit Platform has support in common IDEs and build tools, including IntelliJ IDEA, Eclipse, NetBeans, VS Code, Gradle, Maven, and Ant. In an IDE, run the test class or method using the project’s JUnit configuration. In a build, use the repository’s documented test task or command rather than adding a second, unrelated test setup.
Check dependencies and discovery before changing code
JUnit’s 5.12.0 guide points to dependency metadata, build support instructions, and example projects for Gradle, Maven, and Ant. Dependency declarations vary with the build, selected JUnit version, and test-runner configuration, so confirm them against the actual project rather than pasting an unverified snippet. In particular, ensure Jupiter is available and the Platform can launch its engine at test runtime when the chosen setup requires it.
- Identify the project’s Java runtime and existing build tool, then check that the selected JUnit version supports them.
- Inspect the test dependencies and test task or IDE configuration. Confirm that the Jupiter programming model and required test engine are included.
- Run a single test class from the IDE or build tool. Then run the project’s normal test task to confirm the same tests are discovered in the full suite.
- If Mockito is needed, add its version-matched Jupiter integration to the test setup and run a test that exercises the extension.
Tell discovery failures from assertion failures
- No tests found or class not run: check the test source location, naming conventions, IDE runner, build test task, and whether the JUnit Platform and Jupiter engine are configured.
- Compilation or missing-class error: inspect test-scope dependencies, imports, and version alignment. A parameterized test also needs the matching Jupiter parameterized-test support.
- Assertion failure: the test ran, but actual behavior differed from its expected value. Check the input, setup, expected result, and whether the application behavior is correct.
- Mockito extension or annotation failure: verify that the Jupiter extension dependency matches the Mockito version and that the test class is registered with
@ExtendWith(MockitoExtension.class). - Tests pass alone but fail in a suite: look for shared mutable state, reliance on test order, or resources that are not reset or cleaned up.
How can I keep unit tests reliable and maintainable?
- Use deterministic inputs and avoid relying on real network services or uncontrolled external state.
- Give each test a descriptive name tied to a behavior or condition.
- Make at least one meaningful assertion about an observable result or specified failure.
- Keep tests independent, with explicit setup and appropriate cleanup.
- Use real simple collaborators where they make the test clearer; use mocks for boundaries that benefit from isolation.
- Keep JUnit, its engine, parameterized-test support, Mockito, and the project’s Java runtime version-compatible.
- When a test fails, first determine whether it was discovered and executed; then interpret compilation, configuration, and assertion failures separately.
Or skip the browser setup
For capturing a web page as an artifact alongside a development workflow, ScreenshotNeo offers a screenshot API and MCP server. One GET request can return a PNG, JPEG, WebP, or PDF. For example, request an image from the API (see the ScreenshotNeo API documentation):
Quick Recap
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots, and every feature is on every plan. Sign up for 1,000 free screenshots a month, with no card required.
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.




