mercredi 13 mars 2019

passing static method as parameter in Java

Hello I'm testing the class that has some validating methods and I've been wondering if there is a way to reduce the duplicated code.

@Test
void testCorrectEmailValidator() {
    List<String> correctEmails = Arrays.asList("test@test.com", "test123@test123.com", "test@test.com.in",
            "test.test2@test.com", "test.test2.test3@test.com", "TEST.2test@test.com");

    for (String email : correctEmails) {
        boolean isValid = UserCredentialsValidator.emailValidator(email);
        System.out.println("Email is valid: " + email + ": " + isValid);
        assertTrue(isValid);
    }
}

@Test
void testCorrectUsernameValidator() {
    List<String> correctUsernames = Arrays.asList("username", "123username", "username3", "user2name",
            "USERNAME", "USERNAME123", "123USERNAME123", "2uSERname33");

    for(String username : correctUsernames) {
        boolean isValid = UserCredentialsValidator.usernameValidation(username, userList);
        System.out.println("Username is valid:    " + username + "     : " + isValid);
        assertTrue(isValid);
    }
}

I also have validators for other fields such as username etc. I was thinking about implementing a helper method that would accept: tested credential as String, List but I've got a problem with last parameter - a validating method, not sure how to pass that.

The code i would like to replace with some method is the for loop.

Aucun commentaire:

Enregistrer un commentaire