2

I'm Junit testing a class and had to create some Mockito mock objects. The line of code I'm interested in is this

Mockito.when(emailer.sendEmail(INPUT GOES HERE)).thenReturn(true);

the sendEmail() method of emailer takes in two parameters, and I'm not sure what they will be. Is there a sort of wild card that can be used there to replace the parameters without knowing what they will be?

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
Serge
  • 608
  • 4
  • 12
  • 24

1 Answers1

6

As mentioned in the question comments.

  • Matchers.any(ClassName.class), which is usually what you want. In Mockito 1.x, this stands in for any object, regardless of its type, but by receiving a class it will typically avoid the need for a cast. (According to Mockito contributor Brice in an SO comment, this behavior will change in Mockito 2 and beyond, presumably to behave more like isA as any(MyClass.class) would suggest in English.)
  • Matchers.any(), which will usually require a cast, and isn't a good idea for primitives.
  • Matchers.anyInt() or Matchers.anyShort() (etc), which are good for primitives.
  • Matchers.anyString(), because Strings are a common use-case.

Because Mockito extends Matchers, most of these methods will be available on Mockito, but some IDEs have trouble finding static methods across subclasses. You can find all of them by using import static org.mockito.Matchers.*;.

Read more about all of the matchers available to you at the org.mockito.Matchers documentation.

If you run into trouble, or want to learn more about how these wildcards work under the surface, read more here.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251