Wednesday, March 11, 2026
Cart / 0 $

No products in the cart.

  • Login
  • Register
Bawabaa Digital Solutions
No Result
View All Result
  • Home
  • Products
    • Unlock Premium Access
    • Subscriptions
  • About
    • Terms and conditions
    • Privacy Policy
    • Refund Policy
  • Contact
  • Posts
  • Home
  • Products
    • Unlock Premium Access
    • Subscriptions
  • About
    • Terms and conditions
    • Privacy Policy
    • Refund Policy
  • Contact
  • Posts
No Result
View All Result
Bawabaa Digital Solutions
Home Main

Unit testing – Stub Object in Java

Published on: February 9, 2026
Updated on: February 19, 2026

Here’s another example of using a stub object in Java, but this time for testing a WeatherService that fetches weather data from an external WeatherAPI. We’ll use a stub to simulate the behavior of the WeatherAPI to focus on testing the WeatherService.

Scenario: Testing a Weather Service

The WeatherService class depends on the WeatherAPI to fetch weather information. We want to test the WeatherService without calling the actual external API.


Implementation

Classes:

// Weather API Interface (Dependency)
public interface WeatherAPI {
    String getWeather(String city);
}

// Weather Service (Under Test)
public class WeatherService {
    private final WeatherAPI weatherAPI;

    public WeatherService(WeatherAPI weatherAPI) {
        this.weatherAPI = weatherAPI;
    }

    public String getWeatherInfo(String city) {
        String weather = weatherAPI.getWeather(city);
        if ("Sunny".equals(weather)) {
            return "It's a sunny day!";
        } else if ("Rainy".equals(weather)) {
            return "It's a rainy day!";
        } else {
            return "Weather information unavailable";
        }
    }
}

Stub for WeatherAPI:

We create a simple stub for WeatherAPI that returns hardcoded weather data.

// Stub Implementation for WeatherAPI
public class WeatherAPIStub implements WeatherAPI {
    @Override
    public String getWeather(String city) {
        if ("New York".equals(city)) {
            return "Sunny";
        } else if ("Seattle".equals(city)) {
            return "Rainy";
        }
        return "Unknown";  // Default case for other cities
    }
}

Test Case Using Stub:

Now, let’s write unit tests for WeatherService using the WeatherAPIStub to simulate the weather API’s behavior.

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

public class WeatherServiceTest {

    @Test
    public void testGetWeatherInfoSunny() {
        // Arrange: Use the stub
        WeatherAPI weatherAPIStub = new WeatherAPIStub();
        WeatherService weatherService = new WeatherService(weatherAPIStub);

        // Act: Call the method with "New York" which returns "Sunny" from the stub
        String weatherInfo = weatherService.getWeatherInfo("New York");

        // Assert: Verify the result
        assertEquals("It's a sunny day!", weatherInfo);
    }

    @Test
    public void testGetWeatherInfoRainy() {
        // Arrange: Use the stub
        WeatherAPI weatherAPIStub = new WeatherAPIStub();
        WeatherService weatherService = new WeatherService(weatherAPIStub);

        // Act: Call the method with "Seattle" which returns "Rainy" from the stub
        String weatherInfo = weatherService.getWeatherInfo("Seattle");

        // Assert: Verify the result
        assertEquals("It's a rainy day!", weatherInfo);
    }

    @Test
    public void testGetWeatherInfoUnknownCity() {
        // Arrange: Use the stub
        WeatherAPI weatherAPIStub = new WeatherAPIStub();
        WeatherService weatherService = new WeatherService(weatherAPIStub);

        // Act: Call the method with a city that isn't "New York" or "Seattle"
        String weatherInfo = weatherService.getWeatherInfo("Los Angeles");

        // Assert: Verify the result for the unknown city
        assertEquals("Weather information unavailable", weatherInfo);
    }
}

Explanation:

  1. Stub Implementation (WeatherAPIStub):
    • The stub returns hardcoded responses for specific cities ("Sunny" for “New York” and "Rainy" for “Seattle”).
    • For any other city, it returns "Unknown".
  2. Tests:
    • We write three tests, one for each possible outcome: sunny, rainy, and an unknown city.
    • Each test verifies that the WeatherService correctly interprets the result from the WeatherAPIStub.

Benefits of Using Stubs Here:

  1. Isolation: The test focuses on the WeatherService without being dependent on the actual WeatherAPI.
  2. Controlled Environment: The stub gives predictable outputs, ensuring the unit test is stable and repeatable.
  3. Testing Edge Cases: You can easily simulate different conditions (e.g., cities with specific weather, unknown cities) without calling a real external service.

Donation

Buy author a coffee

Donate
Share11Tweet7Share2
Previous Post

Stub Object in Unit testing with Java

Next Post

Unit Testing

MOUSTAFA

MOUSTAFA

Technology, Engineering and Business Analyst

Categories

  • Main (78)

Recent Posts

  • WordPress Main Subjects – Complete Overview of Core Topics
  • How to Build a Multilingual WordPress Website: Methods, Pros, and Cons
  • Website / Project Development Hierarchy
  • WordPress Hooks Explained: Actions and Filters for Beginners
  • Software Adaptation Maturity Model SAMM
  • What is Screaming Architecture?
  • WordPress Deployment on AWS EC2 (Red Hat / Amazon Linux)
  • eCommerce Platforms Directory: List of Providers by Domain
  • Understanding Modules, Packages, Components, Libraries, Frameworks and Dependencies in Software Design
  • List of Curated YouTube Playlists
  • WordPress Conceptual System Model
  • Computer Science Courses on YouTube
  • Web Hosting Platforms Directory: List of Providers by Domain
  • Computation Theory
  • Software Building Blocks: A Modern Dev Guide
  • Software Architecture and Design
  • List Of Curated Websites
  • WordPress Development Services
  • WordPress Full Courses on YouTube
  • The “Green Padlock” on Localhost Cheat Sheet

HTML Content Title

  • Home
  • Products
  • About
  • Contact
  • Posts
WhatsApp: +201111128344

Bawabaa.com

Welcome Back!

Sign In with Google
OR

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Sign Up with Google
OR

Fill the forms below to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In

You cannot copy content of this page

  • Login
  • Sign Up
  • Cart
No Result
View All Result
  • Home
  • Products
    • Unlock Premium Access
    • Subscriptions
  • About
    • Terms and conditions
    • Privacy Policy
    • Refund Policy
  • Contact
  • Posts
SAVED POSTS

Bawabaa.com

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?