0

Essentially, I have the following:

public class Provider {
  public Map<Enum, Object> get() {
    return Map.of(Enum.ONE, ObjectOne,
                Enum.Two, ObjectTwo);
  }
}

Object value = provider.get().get(Enum.ONE);

I tried mocking this

when(provider.get().get(any())).thenReturn(ObjectOne);

but I got this error

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Object cannot be returned by get()
get() should return Map

I don't want to mock the return of the map, because I only want the map from this particular method to return ObjectOne not all maps in general.

Any ideas how I mock provider.get().get(Enum.ONE) such that it returns ObjectOne?

Object value = provider.get().get(Enum.ONE);

when(provider.get().get(any())).thenReturn(ObjectOne);
Rawr
  • 2,206
  • 3
  • 25
  • 53

2 Answers2

0

Feel like you're approaching the problem wrong. ObjectOne is what you seem to want to stub, not the Map itself

So, define a constructor

public class Provider {

  private ObjectOne one;

  Provider(ObjectOne one) { 
    this.one = one;
  }

  public Map<Enum, Object> get() {
    return Map.of(Enum.ONE, one,
                Enum.Two, ObjectTwo);
  }
}

And use some test like

ObjectOne oo = new ObjectOne();
Provider p = new Provider(oo);
assertSame(oo, p.get().get(Enum.ONE));

Otherwise, you would need to stub the entire method

Map<Enum, Object> map = new HashMap<>();
map.put(Enum.ONE, "foobar");
Provider mock = mock(Provider.class);
when(mock.get()).thenReturn(map);

// obviously the remaining test is pointless because calling mock.get() returns exactly what you already have
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Edit your question with your actual code if this is not what you were looking for – OneCricketeer Sep 17 '21 at 23:22
  • I see what you're getting at here, and unfortunately it's a little more convoluted than I originally hoped. The reason I'm trying to return `ObjectOne` is because there's follow up logic that I'm trying to test. It's difficult to test these follow up paths when the map has a bunch of potential return values. Hence why I'm trying to mock the provider consistently returning a specific object. In the end, I found my answer [here](https://stackoverflow.com/questions/41732361/mock-nested-method-calls-using-mockito). – Rawr Sep 17 '21 at 23:34
0

I found my answer by searching for mock nested method calls using mockito.

@Mock
private ObjectOne mockObjectOne;

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Provider mockProvider;

when(mockProvider.get().get(any())).thenReturn(mockObjectOne);
Rawr
  • 2,206
  • 3
  • 25
  • 53