Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("[email protected]", "[email protected]", "[email protected]",
            "[email protected]", "[email protected]", "[email protected]");

    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.

like image 320
javamat Avatar asked Mar 13 '19 12:03

javamat


1 Answers

I am afraid your tests are of low quality.

The problems that should be fixed immediately include

  1. UserCredentialsValidator.usernameValidation(username, userList); The method shouldn't take the second argument. The place from where that list is retrieved should be concealed from the API consumer.

  2. List<String> correctEmails = Arrays.asList(...) and List<String> correctUsernames = Arrays.asList(...) should be removed. You'd better make the tests parameterised with @ParameterizedTest and @ValueSource.

  3. I'd rather remove the System.out.println statements. They make little sense in tests.


@ParameterizedTest
@ValueSource(strings = {"[email protected]", "[email protected]"})
void testUserEmailValidationWithValidUserEmailShouldPass(String validUserEmail) {
    boolean isValid = UserCredentialsValidator.emailValidator(validUserEmail);
    assertTrue(isValid);
}

@ParameterizedTest
@ValueSource(strings = {"username", "123username"})
void testUserNameValidationWithValidUserNameShouldPass(String validUserName) {
    boolean isValid = UserCredentialsValidator.usernameValidation(validUserName);
    assertTrue(isValid);
}

Now there is nothing to reduce.

like image 191
Andrew Tobilko Avatar answered Oct 31 '22 03:10

Andrew Tobilko