lapots
lapots

Reputation: 13395

easymock throws assertionError with expectaction failed on verify

I've got this method that I want to test.

protected RestResponseStatus validate(INotificationValidator... validations) {
    RestResponseStatus resp = null;
    for (INotificationValidator validation : validations) {
        if (!validation.isValid()) { // <- need to test this
            resp = validation.createErrorResponseStatus();
            break;
        }
    }
    return resp;
}

In order to test it I created class and extended it with class with this method and create test method

@Test
public void nonValidBranchTest() {
    ParameterValidator validator = createMock(ParameterValidator.class);
    validator.isValid();
    expectLastCall().andReturn(false);
    replay(validator);

    this.validate(new ParameterValidator(TEST_STRING));
    verify(validator);

}

But when I try to run test - I've got an error

java.lang.AssertionError: 
   Expectation failure on verify:
     ParameterValidator.isValid(): expected: 1, actual: 0

Upvotes: 0

Views: 5943

Answers (2)

Ren&#233; Link
Ren&#233; Link

Reputation: 51353

Why don't you pass the validator mock to the validate method?

ParameterValidator validator = createMock(ParameterValidator.class);
validator.isValid();
expectLastCall().andReturn(false);
replay(validator);

this.validate(validator);
verify(validator);

If you create a new ParameterValidator instance the mock will of course never be invoked.

As I understand... you want to test if the validate method invokes isValid on the validator and that in case it returns false the validation.createErrorResponseStatus is invoked.

Thus you should also record that behaviour

RestResponseStatus expectedRespStatus = createMock(RestResponseStatus.class);
ParameterValidator validator = createMock(ParameterValidator.class);
validator.isValid();
expectLastCall().andReturn(false);
validator.createErrorResponseStatus().andReturn(expectedRespStatus);
expectLastCall();
replay(validator);
replay(expectedRespStatus);

RestResponseStatus respStatus = this.validate(validator);
assertSame(expectedRespStatus, respStatus);
verify(validator);

Upvotes: 1

Simon Verhoeven
Simon Verhoeven

Reputation: 1323

You should create an instance of your object to be tested in your test class, rather than extending it. Test classes usually don't extend the class under test, but rather mirror the package structure under src\main\test so you can access the protected methods.

The reason there are 0 calls is that you are calling this.validate which is executed on MyClassTest rather than MyClass

Upvotes: 0

Related Questions