具有泛型的模拟方法并在返回类型中扩展 [英] mock method with generic and extends in return type

查看:19
本文介绍了具有泛型的模拟方法并在返回类型中扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用签名 Set< 模拟(使用 mockito)方法?扩展汽车>getCars() 没有抑制警告?我试过了:

Is it possible to mock (with mockito) method with signature Set<? extends Car> getCars() without supress warnings? i tried:

XXX cars = xxx;
when(owner.getCars()).thenReturn(cars);

但无论我如何声明 cars,我总是会遇到编译错误.例如,当我这样声明时

but no matter how i declare cars i alway get a compilation error. e.g when i declare like this

Set<? extends Car> cars = xxx

我得到标准的通用/模拟编译错误

i get the standard generic/mockito compilation error

The method thenReturn(Set<capture#1-of ? extends Car>) in the type OngoingStubbing<Set<capture#1-of ? extends Car>> is not applicable for the arguments (Set<capture#2-of ? extends Car>)

推荐答案

使用 doReturn-when 备用存根语法.

Use the doReturn-when alternate stubbing syntax.

被测系统:

public class MyClass {
  Set<? extends Number> getSet() {
    return new HashSet<Integer>();
  }
}

和测试用例:

import static org.mockito.Mockito.*;

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

public class TestMyClass {
  @Test
  public void testGetSet() {
    final MyClass mockInstance = mock(MyClass.class);

    final Set<Integer> resultSet = new HashSet<Integer>();
    resultSet.add(1);
    resultSet.add(2);
    resultSet.add(3);

    doReturn(resultSet).when(mockInstance).getSet();

    System.out.println(mockInstance.getSet());
  }
}

不需要错误或警告抑制

这篇关于具有泛型的模拟方法并在返回类型中扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆