18

抑制警告なしで署名付きの(mockitoを使用した)メソッドをモックすることは可能Set<? extends Car> getCars()ですか?私は試した:

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

しかし、どのように宣言してもcars、常にコンパイルエラーが発生します。例えば私がこのように宣言するとき

Set<? extends Car> cars = xxx

標準のgeneric/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>)
4

1 に答える 1

38

doReturnを使用します-代替スタブ構文の場合。

テスト対象システム:

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

エラーや警告の抑制は必要ありません

于 2012-05-11T19:23:53.330 に答える