mercredi 28 octobre 2015

Verify with mocks an error message where result can change based on id

So I've got some unit tests where I'm mocking a number of objects, and using those to write tests.

I'm setting the mock objects using anyInt() argument matcher. I want to verify a method called displayErrorMessage(String errorMsg). This method accepts a string, and outputs it into the GUI. The String it accepts is formatted before being sent to the display method with the relevant member Id.

I want to use the argument matcher again in a String format to pass the correct error message to the verify statement.

String.format("Member %d cannot borrow at this time.", anyInt());

I know anyInt() returns zero. I can just manually verify the displayErrorMessage() assuming this, but that seems incorrect.

Current test code:

@Test
public void borrowingRestrictedWhenCardSwipedHasExceededFineLimit() throws Exception {
    when(memberDAO.getMemberByID(anyInt())).thenReturn(member);
    when(member.hasReachedFineLimit()).thenReturn(true);

    ctl.initialise();
    ctl.cardSwiped(anyInt());

    String errorMessage = "Member %d cannot borrow at this time.";
    errorMessage = String.format(errorMessage, anyInt());

    verify(ui).displayErrorMessage(errorMessage);
}

This verify would work in this situation:

verify(ui).displayErrorMessage("Member 0 cannot borrow at this time.");

If I'm approaching this incorrectly, whats a better way to do this?

Aucun commentaire:

Enregistrer un commentaire