23

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

risingTide
  • 1,754
  • 7
  • 31
  • 60
nkr1pt
  • 4,691
  • 5
  • 35
  • 55

6 Answers6

26

You could use .andThrow(new AssertionFailedError()).anyTimes(); - this is the same exception that Assert.fail() throws, but is less verbose than making an Answer.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • 2
    Maybe 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
10

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();
David Nguyen
  • 221
  • 2
  • 9
8

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 NiceMocks, where default values are returned when calling for not recorded methods.

So a solution can be not to use NiceMocks.

Vic
  • 1,778
  • 3
  • 19
  • 37
  • 2
    I 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
  • 1
    It 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
1

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() ?

Christian Strempfer
  • 7,291
  • 6
  • 50
  • 75
1

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.

Henri Tremblay
  • 666
  • 5
  • 2
0

I managed to come up with a solution:

expectLastCall().andAnswer(new IAnswer() {
    public Object answer() {
        Assert.assertFail();
        return null;
    }
});
nkr1pt
  • 4,691
  • 5
  • 35
  • 55