0

What's the purpose of Custom Matcher and how we can compare with

Object.equal().

I have a problem that Object.equal() solve easily while passing parameters in when() but some time I need to use Matchers. I need to know what would be the behavior and how it would be executed.

My current code is:

@Test
public void myTest() {
  when(service.foo(xyzService, new ARequest(1, "A"))).thenReturn(new AResponse(1, "passed"));
  when(service.foo(xyzService, new ARequest(2, "2A"))).thenReturn(new AResponse(2, "passed"));
  when(service.foo(xyzService, new BRequest(1, "B"))).thenReturn(new BResponse(112, "passed"));

  c.execute();
}

currently it works fine but in my actual business case i am not able to mock xyzService it a method level variable. I want o use any() instead of xyzService. but in this case everything brokers.

Zeeshan Bilal
  • 1,147
  • 1
  • 8
  • 22
  • 2
    Show the code.. – nhouser9 Jan 21 '17 at 06:36
  • Possible duplicate of [What's the difference between Mockito Matchers isA, any, eq, and same?](http://stackoverflow.com/questions/30890011/whats-the-difference-between-mockito-matchers-isa-any-eq-and-same) – David Rawson Jan 21 '17 at 06:40

2 Answers2

2

With when, you train the mock method either on fixed parameters or on matchers. We can't mix. If you want to use the any() matcher for one parameter, you have to convert the other param to a matcher too:

when(service.foo(any(), eq(new ARequest(1, "A")))).thenReturn(new AResponse(1, "passed"));

If this doesn't work for your test case, then either the equals implemention in ARequest is broken or the test or the test object (i.e.: the expected method call with any service and this request never happens in the tested code)

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
1

Matchers are typically not needed except in complex object structures or if you want to base equality on different criteria then what the objects equal method has defined.

Equality Example

For instance, take this simplified example (pseudo code):

class test {
   int x,y,z;

   bool equals() {
     return x == y && x == z && y == z
   }
 // should override hashCode as well

}

But then in your test you only cared about x and z matching you could write a matcher to perform this validation. For the given example, obviously it doesn't make sense because the comparison is so basic.

Complex Objects

I have created generic matchers in the past that can crawl a whole object graph performing a field by field comparison. They could also be used to perform different 'matching' criteria based on context. I say could because this generally breaks the Single Responsibility Principle.

gwnp
  • 1,127
  • 1
  • 10
  • 35