mock method with generic and extends in return type

后端 未结 1 1371
北恋
北恋 2020-12-18 21:19

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

XXX cars = xxx         


        
相关标签:
1条回答
  • 2020-12-18 21:42

    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

    0 讨论(0)
提交回复
热议问题