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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

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

  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • MCP Servers: The Technical Debt That Is Coming
  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
43.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, DZone MVB. 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!