What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a new Java unit test, use JUnit Jupiter: create a focused test method annotated with @Test, execute the code under test, and assert an observable result. Run it through the project’s existing IDE or Maven or Gradle build, and add Mockito only when a collaborator needs to be isolated. Match JUnit, Mockito, and Java versions to the project; the examples below follow the JUnit 5.12.0 guide and Mockito 5.17.0 API.

How do I write unit tests in Java?

A unit test checks a small piece of behavior independently enough that its result is clear when it passes or fails. Choose a useful boundary first: test a method or class’s externally observable behavior, not every private implementation detail. A test is most useful when it has a clear setup, action, and assertion.

Here is a minimal example using JUnit Jupiter. The test exercises a small class and checks the returned value:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class PriceCalculator {
    int totalWithTax(int subtotal, int tax) {
        return subtotal + tax;
    }
}

class PriceCalculatorTest {
    @Test
    void addsTaxToSubtotal() {
        PriceCalculator calculator = new PriceCalculator();

        int total = calculator.totalWithTax(100, 8);

        assertEquals(108, total);
    }
}

@Test marks the method for Jupiter discovery. assertEquals(expected, actual) fails with an assertion error if the values differ. Prefer assertions that communicate the intended outcome; a test that only executes code without checking anything does not establish that the behavior is correct.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • 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.

Test specified failure behavior

When invalid input is supposed to fail, assert the exception rather than catching it manually. The following example assumes that rejecting a negative quantity is part of the method’s contract:

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void rejectsNegativeQuantity() {
    PriceCalculator calculator = new PriceCalculator();

    IllegalArgumentException error = assertThrows(
        IllegalArgumentException.class,
        () -> calculator.totalWithTax(-1, 0)
    );

    assertEquals("subtotal must not be negative", error.getMessage());
}

Use an exception assertion only for failure behavior the code is meant to guarantee. If the message is not part of the contract, asserting the exception type alone is less brittle.

Use parameterized tests for representative inputs

If the same rule should hold for several inputs, a parameterized test avoids repeating the test method. Jupiter provides parameterized-test support; for a CSV source, include the parameterized-test API and the required parameter source in the project’s test dependencies.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

class PriceCalculatorTest {
    @ParameterizedTest
    @CsvSource({
        "100, 8, 108",
        "0, 0, 0",
        "50, 5, 55"
    })
    void addsTax(int subtotal, int tax, int expected) {
        PriceCalculator calculator = new PriceCalculator();

        assertEquals(expected, calculator.totalWithTax(subtotal, tax));
    }
}

Pick values that represent meaningful cases—ordinary input, boundary input, and any important special case—rather than generating many values without a reason. Nested tests can also group tests by context when that structure makes the behavior easier to understand.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 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.

How should JUnit 5 be set up?

JUnit 5 is a family of components, not a single library: JUnit Platform launches test engines, JUnit Jupiter provides the programming and extension model for new tests, and JUnit Vintage lets older JUnit 3 and JUnit 4 tests run on the Platform. For new tests, write Jupiter tests and ensure the selected build configuration includes the Jupiter engine when runtime discovery requires it.

The JUnit 5.12.0 guide states that JUnit 5 requires Java 8 or higher at runtime. That is the requirement in that versioned guide, not a guarantee that every newer JUnit version or project configuration supports the same runtime. Check the compatibility information for the exact JUnit version and the Java runtime used by local builds and CI. Consult the JUnit 5.12.0 User Guide for its dependency metadata and build-support guidance; use the version already managed by your project when possible rather than copying an unpinned snippet into a different build.

Build-tool and IDE setup

The Platform is supported by common IDEs and build tools, including IntelliJ IDEA, Eclipse, NetBeans, VS Code, Gradle, Maven, and Ant. The exact setup depends on project plugins, dependency management, and versions, so confirm that Jupiter tests are discovered by the repository’s real execution path.

  • In an IDE, run the test class or an individual test with the IDE’s test runner, using the project SDK and test classpath.
  • For Maven or Gradle, use the test task already defined by the repository and inspect its output to confirm that Jupiter tests were found and executed.
  • If the IDE runs a test but the build does not, or vice versa, compare the JDK, test dependencies, plugins, and test-source directories used by those paths.

For a project-specific walkthrough of Gradle setup, running tests, assertions, parameterized tests, exception tests, and grouping, see JetBrains’ Writing JUnit 5 Tests.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • 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 do test lifecycle and isolation work?

By default, Jupiter creates a fresh test-class instance for each test method. This helps prevent mutable instance fields from leaking state between tests, but it does not make shared static state, external services, files, or databases independent. Tests should not rely on execution order or on another test having prepared state.

Use lifecycle methods when setup is genuinely shared

@BeforeEach runs before each test method and is appropriate for creating a fresh fixture used by multiple tests. @AfterEach runs after each test method and is useful for cleanup such as closing resources. Keep setup small and relevant: elaborate fixtures can obscure what a test is checking. A test should be understandable on its own, even if it uses a helper.

Jupiter also supports lifecycle controls, assumptions, tags, and filtering. Use an assumption when a test only applies under a condition; use tags and filters when the project needs to select subsets of tests. These features should make the test suite clearer, not hide tests that ought to run routinely.

How do I use JUnit 5 with Mockito?

Mockito is optional. Use it when a class depends on a collaborator whose behavior should be controlled for the test—for example, a service that delegates persistence to a repository. Do not mock a class simply because it is available: a real, lightweight collaborator may make the test simpler and more representative.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • 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

With Mockito 5.17.0, the JUnit Jupiter extension can initialize annotated mocks. The example below stubs one repository result and asserts the service’s returned behavior:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock
    UserRepository repository;

    @Test
    void returnsUserNameForExistingUser() {
        when(repository.findById(7L)).thenReturn(Optional.of(new User(7L, "Mina")));
        UserService service = new UserService(repository);

        String name = service.nameFor(7L);

        assertEquals("Mina", name);
    }
}

This assumes application classes with the indicated constructor and method, and a repository method returning Optional<User>; adapt those names and types to the project’s code. The assertion checks the service’s observable result. Add interaction verification only when the interaction itself matters to the contract, such as ensuring a payment is not submitted twice. Avoid asserting a long sequence of internal calls that can change without changing correct behavior.

The Mockito 5.17.0 API documentation describes the Jupiter extension and strict-stubbing facilities. Strictness can help expose unused or mismatched stubs; Mockito’s default style is described as loose, so use stubbing deliberately and remove setup that the test does not need.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I diagnose a Java unit test that will not run?

First separate test discovery or configuration problems from assertion failures. A discovered test that runs and fails an assertion usually points to a mismatch between expected and actual behavior. A test that does not start, is not found, or fails during extension initialization usually points to the runtime, dependency, build, or IDE setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 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.
  • No tests found: Confirm the class is in the configured test source directory, the method has Jupiter’s @Test, and the Platform/Jupiter engine is available to the runner. Check that the IDE and build use the intended test framework.
  • Compilation errors for JUnit imports: Check that the Jupiter API is on the test compile classpath and that the test uses the imports for the version selected by the project.
  • Tests run in the IDE but not CI, or the reverse: Compare Java versions, dependency resolution, test plugins, and runner configuration. Prefer the repository’s documented build command as the shared baseline.
  • Mockito extension or annotation errors: Verify that the Mockito Jupiter extension dependency is present at test runtime and that the class uses @ExtendWith(MockitoExtension.class). Check that Mockito and JUnit versions are compatible with the project’s setup.
  • Unexpected mock behavior: Make sure the stub matches the actual arguments and that the test uses the same mock instance injected into the class under test. Remove unused stubs or configure only behavior needed for the scenario.
  • Tests pass alone but fail in a suite: Look for mutable static state, reused external resources, order dependencies, and incomplete cleanup. Make each test establish its own preconditions.
  • Assertion failure: Read the expected and actual values first. Then check the setup inputs and the behavior contract; do not weaken an assertion merely to make the suite green.

What makes a unit test maintainable?

  • Use deterministic inputs and avoid dependence on test order, clock time, network state, or shared mutable data unless the test explicitly controls those factors.
  • Give tests descriptive names that identify the behavior or condition.
  • Make each test’s setup, action, and meaningful assertion easy to locate.
  • Prefer real simple collaborators; mock only boundaries whose behavior needs control or isolation.
  • Keep dependency versions aligned with the project’s JDK, build, IDE, and CI configuration.

Or skip the browser setup

For screenshot examples in documentation or test fixtures, an API call can provide an image without configuring a browser runner. ScreenshotNeo is a website screenshot API and MCP server: it removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed; and its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000.

One cURL request, using the documented API shape:

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 setup and options. ScreenshotNeo is made by Yorker Media. Sign up free for 1,000 screenshots a month with no card.

Frequently Asked Questions

Does a basic JUnit test need Mockito?

No. Mockito is optional and is useful when a collaborator needs to be controlled or isolated; a straightforward unit can be tested directly.

Can JUnit 5 run older JUnit tests?

Yes. JUnit Vintage runs JUnit 3 and JUnit 4 tests on the JUnit Platform, while Jupiter is the programming model for new JUnit 5 tests.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.