eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

Partner – Diagrid – NPI (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

1. Overview

A UrlConnection is an abstract class that provides an interface to work with resources on the web, such as retrieving data from URLs and sending data to them.

When writing unit tests, we’ll typically want a way to simulate network connectivity and responses without actually making actual network requests.

In this tutorial, we’ll look at several ways we can mock a URL Connection in Java.

2. A Simple URL Fetcher Class

Throughout this tutorial, the focus of our tests will be a simple URL fetcher class:

public class UrlFetcher {

    private URL url;

    public UrlFetcher(URL url) throws IOException {
        this.url = url;
    }

    public boolean isUrlAvailable() throws IOException {
        return getResponseCode() == HttpURLConnection.HTTP_OK;
    }

    private int getResponseCode() throws IOException {
        HttpURLConnection con = (HttpURLConnection) this.url.openConnection();
        return con.getResponseCode();
    }
}

For demonstration purposes, we have one public method isUrlAvailable(), that indicates whether the URL for the given address is available. The return value is based on the status code from the HTTP response message we receive.

3. Unit Testing Using Pure Java

Normally the first port of call for working with mocks is to use a third-party testing framework. However, in some situations, this may not be a viable option.

Luckily the URL class provides a mechanism that allows us to provide a custom handler that knows how to make a connection. We can use this to provide our handler, which will return a dummy connection object and response.

3.1. Support Classes

For this approach, we’ll need several support classes. Let’s start by defining a MockHttpURLConnection:

public class MockHttpURLConnection extends HttpURLConnection {

    protected MockHttpURLConnection(URL url) {
        super(url);
    }

    @Override
    public int getResponseCode() {
        return responseCode;
    }

    public void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }

    @Override
    public void disconnect() {
    }

    @Override
    public boolean usingProxy() {
        return false;
    }

    @Override
    public void connect() throws IOException {
    }
}

As we can see, this class is a simple extension with a minimal implementation of the HttpURLConnection class. The important part here is that we provide a mechanism for setting and getting the HTTP response code.

Next, we’ll need a mock stream handler that returns our newly created MockHttpURLConnection:

public class MockURLStreamHandler extends URLStreamHandler {

    private MockHttpURLConnection mockHttpURLConnection;

    public MockURLStreamHandler(MockHttpURLConnection mockHttpURLConnection) {
        this.mockHttpURLConnection = mockHttpURLConnection;
    }

    @Override
    protected URLConnection openConnection(URL url) throws IOException {
        return this.mockHttpURLConnection;
    }
}

Finally, we need to provide a stream handler factory that will return our newly created stream handler:

public class MockURLStreamHandlerFactory implements URLStreamHandlerFactory {

    private MockHttpURLConnection mockHttpURLConnection;

    public MockURLStreamHandlerFactory(MockHttpURLConnection mockHttpURLConnection) {
        this.mockHttpURLConnection = mockHttpURLConnection;
    }

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        return new MockURLStreamHandler(this.mockHttpURLConnection);
    }
}

3.2. Putting It All Together

Now that we have our support classes ready, we can go ahead and write our first unit test:

private static MockHttpURLConnection mockHttpURLConnection;

@BeforeAll
public static void setUp() {
    mockHttpURLConnection = new MockHttpURLConnection(null);
    URL.setURLStreamHandlerFactory(new MockURLStreamHandlerFactory(mockHttpURLConnection));
}

@Test
void givenMockedUrl_whenRequestSent_thenIsUrlAvailableTrue() throws Exception {
    mockHttpURLConnection.setResponseCode(HttpURLConnection.HTTP_OK);
    URL url = new URL("https://www.baeldung.com/");

    UrlFetcher fetcher = new UrlFetcher(url);
    assertTrue(fetcher.isUrlAvailable(), "Url should be available: ");
}

Let’s walk through the key parts of our test:

  • First, we start by defining the setUp() method, where we create our MockHttpURLConnection and inject this into the URL class via the static method setURLStreamHandlerFactory().
  • Now we can start to write the body of our test. First, we need to set the expected response code using the setResponseCode() method on our mockHttpURLConnection variable.
  • Then we can create a new URL and construct our UrlFetcher before finally asserting on the isUrlAvailable() method

When we run our test, we should always get the same behavior irrespective of whether the web address is available. A great test to ensure this is to switch off your Wi-Fi or network connection and check that the tests still behave in exactly the same way.

3.3. Problems With This Approach

Although this solution works and does not rely on third-party libraries, it’s a bit cumbersome for several reasons.

First of all, we need to create several mock support classes, and as our testing needs become more complex, our mock objects will also grow more complex. For example, if we need to start mocking different response bodies.

Likewise, our test has some important setup where we mix static method calls with new instances of the URL class. This is confusing and will likely lead to unexpected results further down the line.

4. Working With Mockito

In this next section, we’ll see how we can simplify our tests using Mockito, a well-known unit testing framework.

First, we’ll need to add the mockito dependency to our project:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>5.11.0</version>
    <scope>test</scope>
</dependency>

Now we can define our test:

@Test
void givenMockedUrl_whenRequestSent_thenIsUrlAvailableFalse() throws Exception {
    HttpURLConnection mockHttpURLConnection = mock(HttpURLConnection.class);
    when(mockHttpURLConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND);
        
    URL mockURL = mock(URL.class);
    when(mockURL.openConnection()).thenReturn(mockHttpURLConnection);
        
    UrlFetcher fetcher = new UrlFetcher(mockURL);
    assertFalse(fetcher.isUrlAvailable(), "Url should be available: ");
}

This time around, we create a mock URL connection using Mockito’s mock method. We then configure the mock object to return a mock HTTP URL connection when its openConnection method is called. Of course, our mock HTTP connection already contains a stubbed response code.

We should note that for versions of Mockito below 4.8.0 we’ll likely receive an error when running this test:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.net.URL
Mockito cannot mock/spy because :
 - final class

This happens because the URL is a final class, and in previous versions of Mockito, it was not possible to mock final types and methods straight out of the box.

In order to resolve this issue, we can simply add an extra dependency to our pom.xml:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>5.2.0</version>
    <scope>test</scope>
</dependency>

Now our test will run successfully!

5. Working With JMockit

In our final example, we’ll look at another testing library called JMockit for completeness.

First, we’ll need to add the jmockit dependency to our project:

<dependency> 
    <groupId>org.jmockit</groupId> 
    <artifactId>jmockit</artifactId> 
    <version>1.49</version>
</dependency>

Now we can go ahead and define our test class:

@ExtendWith(JMockitExtension.class)
class UrlFetcherJMockitUnitTest {

    @Test
    void givenMockedUrl_whenRequestSent_thenIsUrlAvailableTrue(@Mocked URL anyURL,
      @Mocked HttpURLConnection mockConn) throws Exception {
        new Expectations() {{
            mockConn.getResponseCode();
            result = HttpURLConnection.HTTP_OK;
        }};

        UrlFetcher fetcher = new UrlFetcher(new URL("https://www.baeldung.com/"));
        assertTrue(fetcher.isUrlAvailable(), "Url should be available: ");
    }
}

One of the strongest points of JMockit is its expressibility. In order to create mocks and define their behavior, instead of calling methods from the mocking API, we just need to define them directly.

6. Conclusion

In this article, we learned several ways we could mock a URL connection to write stand-alone unit tests that don’t rely on any external services. First, we looked at an example using vanilla Java and then explored two other options working with Mockito and JMockit.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook – Mockito – NPI (tag=Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

>> Download the eBook

eBook Jackson – NPI EA – 3 (cat = Jackson)