java 具有泛型和返回类型扩展的模拟方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10554955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:32:31  来源:igfitidea点击:

mock method with generic and extends in return type

javagenericsmockito

提问by piotrek

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

是否可以在Set<? extends Car> getCars()没有抑制警告的情况下模拟(使用 mockito)带有签名的方法?我试过:

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

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

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

Set<? extends Car> cars = xxx

i get the standard generic/mockito compilation error

我得到标准的泛型/mockito 编译错误

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>)

回答by Tom Tresansky

Use the doReturn-when alternate stubbing syntax.

使用 doReturn-when 替代存根语法。

System under test:

被测系统:

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

and the test case:

和测试用例:

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());
  }
}

No errors or warning suppression needed

不需要错误或警告抑制