具有泛型的模拟方法并在返回类型中扩展

2022-01-14 00:00:00 mockito java generics

是否可以使用签名 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());
  }
}

不需要错误或警告抑制

相关文章