JMock - several invocations with different arguments
Asked Answered
C

1

6

The method I want to test is calling a mock method with different arguments:

public void methodToTest(){
   getMock().doSomething(1);
   getMock().doSomething(2);
   getMock().doSomething(3);
}

In my unit test I want to know, if methodToTest really is calling those methods with exactly those arguments. This is the code I wrote:

@Test
public void myMockTest(){
    oneOf(mock).doSomething(1);
    oneOf(mock).doSomething(2);
    oneOf(mock).doSomething(3);
}

At (2) I get an "Unexpected invocation" - as if it couldn't distinguish different arguments. So I've tried that one:

exactly(3).of(mock).doSomething(with(Matchers.anyOf(same(1), same(2), same(3))));

But this also didn't do what I've expected.

Finally, this one worked:

exactly(3).of(mock).doSomething(with(any(Integer.class)));

So I know, that my method was called 3 times with any Integer number. Is there any way to make sure, it's exactly the argument(s) I have passed?

Corbeil answered 1/6, 2012 at 15:23 Comment(2)
Well, the posted code works just fine. JMock seems to have problems with casted objects, though.. Solved so far.Corbeil
what are the casting problems? Can you give us more detail?Gumm
G
2

Did you surround the expectations with a checking block?

context.checking(new Expectations() {{
  oneOf(mock).doSomething(1);
  oneOf(mock).doSomething(2);
  oneOf(mock).doSomething(3);
}});

Also, are you aware the jmock does not enforce sequence unless you do so explicitly?

Gumm answered 6/6, 2012 at 13:16 Comment(1)
I used the correct syntax and JMock is using a default sequence without having to say so. I'm still not sure, what was causing the problems - I'm using a list and adding an element. Asserting equality to the object and the object got by list.get(0) returned false, altough it IS the same object. Overriding equals/hashcode in my object class solved the problem.Corbeil

© 2022 - 2024 — McMap. All rights reserved.