Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

java - mock method with generic and extends in return type

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

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>)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the doReturn-when alternate stubbing syntax.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...