DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Generics in Java and Their Implementation
  • Creating Your Swiss Army Knife on Java Test Stack
  • Projections/DTOs in Spring Data R2DBC
  • Fluent Assertions Reloaded

Trending

  • AI-Era Cybersecurity, Part 1: Mapping Glasswing, Daybreak, Lightwell and the Tools Racing to Find and Fix Bugs
  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • When One Docker Swarm Replica Became Unreachable Over an Overlay Network: A Production Case With Traefik
  • Claude Code Superpowers: The 5-Tool Stack That Ends Limits and Context Amnesia

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Mocking Method with Wildcard Generic Return Type

Mocking Method with Wildcard Generic Return Type

By 
Ivan Zerin
·
Apr. 27, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
44.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

[Ivan Zerin provides a primer on mocking methods that contain generic return types.]

There are several cases where construction when().thenReturn is not suitable during Unit tests. One of then generic return type. I have faced such issue, let's take a look. There is a method in interface declaration:

public interface FooInterface {    
    public Iterable<? extends SomeClass> getList();
    ...
}

Implementation looks like this:

public class Foo implements FooInterface {

    public List<SomeChildClass> getList() {
        ...
    }

    ...
}

At first mocking of such method should not be something unusual:

public class UnitTest {
    @Mock private FooInterface mockFoo;

    @Test
    public void someUnitTest() {
        ...
        List<SomeChildClass> testList = generateTestList();
        when(mockFoo.getList())
          .thenReturn(testList);
    }
}

But this code won't compile with error: Cannot resolve method 'thenReturn(List<SomeChildClass>). Seems to be some mistake, cause returned type are correct from the interface point of view.

This error happening cause compiler can not gurantee that returned type of method getList() will be List<SomeChildClass>. Actually return type of method getList() in this case is Iterable<? extends SomeClass> and this means "Return some Iterable object with any objects that extends SomeClass". Let's rename this type as 'X'. So when(mockFoo.getList()) will create object OngoingStubbing<Iterable<X>> and it has method thenReturn(Iterable<X>). Compiler can not tell what type X before runtime and cannot perform safe cast from List<SomeChildClass> to Iterable<X> (we perfrom actuall call of method thenReturn(List<SomeChildClass>)).

Sounds a little tricky but let's assume that SomeClass is standard Java class Number. Then classes Integer and Double are both fulfill the criteria of List<? extends Number>. Let's say that as return type of mock we will use List<Double>, in this case, compiler should be ready that actual work with code during runtime will be performed with List<Integer> too, but it is clearly that cast from Double to Integer will be incorrect (try to cast double value 12.6 to int).

You could argue that in the case of mockito compiler won't need to bother about the casting of returned type because call of original method would not produce anything, but it is known by mockito. From compiler point of view, it is only Java code, that should be checked for safety and correctness before compiling.

Ok, so how we should deal with such cases in mockito?

Use doReturn() method:

doReturn(testList).when(mockFoo).getList();

Such expression is not type safe, so it were designed for exceprional cases, so use it only when you cannot use standart when().thenReturn(), which is the type-safe, elegant and more readable syntax.

Mockito Object (computer science) Java (programming language) Interface (computing) Correctness (computer science) Testing Syntax (programming languages) Implementation

Published at DZone with permission of Ivan Zerin. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Generics in Java and Their Implementation
  • Creating Your Swiss Army Knife on Java Test Stack
  • Projections/DTOs in Spring Data R2DBC
  • Fluent Assertions Reloaded

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook