Is this possible?
I tried with EasyMock.expectLastCall().times(0);
but EasyMock complains that times must be >=1

- 1,754
- 7
- 31
- 60

- 4,691
- 5
- 35
- 55
-
See http://stackoverflow.com/questions/859031/easymock-void-methods , not sure it's a dupe though. – philant Sep 14 '10 at 18:45
-
5It isn't a duplicate. – hiergiltdiestfu Jul 22 '13 at 10:30
6 Answers
You could use .andThrow(new AssertionFailedError()).anyTimes();
- this is the same exception that Assert.fail()
throws, but is less verbose than making an Answer
.

- 77,785
- 15
- 98
- 110
-
2Maybe adding a good description on why the test failed further improves this solution (which is the best of all given here IMO). – qben Feb 12 '15 at 10:27
with easymock 3.0, you need to add a .anyTimes() on the expectLastCall or the test will fail:
Expectation failure on verify: myMethod(): expected: 1, actual: 0`
based on nkr1pt example:
expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
Assert.assertFail();
return null;
}
}).anyTimes();

- 221
- 2
- 9
-
3
-
1While this is a working answer, I like the one from David Wallace better since it's less verbose. – qben Feb 12 '15 at 10:25
The fact that some method is not called is controlled by Mock
or StrictMock
. They will throw an exception, when that not recorded method is called. This problem occurs only when using NiceMock
s, where default values are returned when calling for not recorded methods.
So a solution can be not to use NiceMock
s.

- 1,778
- 3
- 19
- 37
-
2I strongly disagree with the conclusion. Maybe, in this case, nice mock is not the best choice. But if you want to make sure one method will not get called, in fact this is the only thing you want to test, it's better to emphasize this with a mocked method that fails with an appropriate message. – qben Feb 12 '15 at 10:24
-
1It is a good argument. I wanted to point this one out, since I had stumbled upon why I cannot specify `times(0)`. And only later I realized, that that kind of contradicts with the idea of nice mocking, and not nice mocking does not allow unrecorded methods to be executed. Throwing an assert exception as the answer seemed more like a workaround for me and that 0 method calls should be specified using not nice mocks. Maybe I am a bit assertive in the conclusion. I'll just correct it. – Vic Feb 12 '15 at 11:54
Looks like a bug to me. The internal class Range
does not allow to set a maximum less than 1.
Couldn't you mock that method, and just call Assert.fail()
?

- 7,291
- 6
- 50
- 75
If you expect your method not to be called then just don't record it. But I agree it won't work with a nice mock.

- 666
- 5
- 2
I managed to come up with a solution:
expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
Assert.assertFail();
return null;
}
});

- 4,691
- 5
- 35
- 55
-
1Agreed that this doesn't work. The correct answer is from David Nguyen. – dhaag23 Sep 02 '14 at 21:01