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
Over 2 million developers have joined DZone.
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

  • Spring AI Advisors: Chat Memory, Token Tracking, and Message Logging
  • Securing the AI Host: Spring AI MCP Server Communication With API Keys
  • Why Round-Robin Won't Save You: Load Balancing Challenges in Data Streaming Services With Heterogeneous Traffic
  • Jakarta EE 12: Entering the Data Age of Enterprise Java
  1. DZone
  2. Coding
  3. Java
  4. Mocking Method with Wildcard Generic Return Type

Mocking Method with Wildcard Generic Return Type

By 
Ivan Zerin user avatar
Ivan Zerin
·
Apr. 27, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
44.4K Views

Join the DZone community and get the full member experience.

Join For Free

[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

The likes didn't load as expected. Please refresh the page and try again.

  • 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