Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito anyMapOf nested generics

I am attempting to verify that a method with the following signature was called:

public void process(Map<String, Set<String>> data) {
  ...
}

The nested parameterized Set is causing me difficulties. I can get it to verify correctly with the any() matcher like so:

verify(dataProcessor).process(Matchers.<Map<String, Set<String>>> any());

As described in Mockito: Verifying with generic parameters although annoyingly it doesn't work if I do a direct static import of Matchers.any and call it as just:

verify(dataProcessor).process(<Map<String, Set<String>>> any())

But anyMapOf(clazz, clazz) seems the more appropriate matcher in this case. Since you can't do Set.class I'm not sure how you would do this. The following doesn't work because of the lack of generic:

verify(dataProcessor).process(anyMapOf(String.class, Set.class));

Is it possible to verify this situation with anyMapOf or should I stick with Matchers.<>any()?

like image 805
Ben Pennell Avatar asked Feb 14 '14 15:02

Ben Pennell


1 Answers

There's no way to use anyMapOf to do this. It's designed to help with the simple case of mapping simple classes to simple classes in Java 7, and yours is more complex than that.

Java 8 parameter inference improved, so in Java 8, you can just use any().

verify(dataProcessor).process(Matchers.any());

Barring that, the best way to make this look is either like you wrote above:

verify(dataProcessor).process(Matchers.<Map<String, Set<String>>>any());

Or by extracting the matcher to a static function, which gives Java just enough information it needs to infer the type on its own:

@Test public void yourTest() {
  // ...
  verify(dataProcessor).process(anyStringSetMap());
}

private static Map<String, Set<String>> anyStringSetMap() {
  return any();
}

(Caveat: Note that the return value of anyStringSetMap() is null; it's the side-effect of calling any that you're looking for. The extracted method is just to inform the Java compiler of the expected return type; beware that doing anything fancier will probably break in really-quite-interesting ways.)

like image 86
Jeff Bowman Avatar answered Oct 14 '22 03:10

Jeff Bowman