lundi 22 février 2016

Should tests re-use constants?

Say I have code for input validation,

public static final String inputHasNumbers = "Input should not have numbers. Your input was %s."

public String errorMessage(String input) {
    if (containsNumber(input)) {
        return String.format(inputHasNumbers, input);
    } 
    return "";
}

In the unit test for this, which should be favoured?

assertEquals(String.format(InputValidation.inputHasNumbers, "555" ) , InputValidation.errorMessage("555"))

or

assertEquals("Input should not have numbers. Your input was 555." , InputValidation.errorMessage("555"))

I have looked at Do you use constants from the implementation in your test cases?,

But the context here is different. It is not particularly clear (to me, at least) when one should be favoured over the other.

In this particular context of generating status messages, although it introduces magic Strings in the tests, shouldn't we want the tests to be explicit what the validation message should be?

Aucun commentaire:

Enregistrer un commentaire