Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>)
like image 244
piotrek Avatar asked May 11 '12 16:05

piotrek


People also ask

What is the difference between doReturn and thenReturn?

Following are the differences between thenReturn and doReturn : * Type safety : doReturn takes Object parameter, unlike thenReturn . Hence there is no type check in doReturn at compile time. In the case of thenReturn , whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised.

Can we mock a method in Junit?

While doing unit testing using junit you will come across places where you want to mock classes. Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls.

Does mock object call real method?

Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().

What is doReturn in Mockito?

You can use doReturn-when to specify a return value on a spied object without making a side effect. It is useful but should be used rarely. The more you have a better pattern such as MVP, MVVM and dependency injection, the less chance you need to use Mockito. spy .


1 Answers

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

like image 89
Tom Tresansky Avatar answered Sep 20 '22 14:09

Tom Tresansky