dimanche 1 décembre 2019

Java NegativeTest private method with Reflection to catch custom ApplicationException

So I'm testing a AccountService class with a mocked databaselayer. In this AccountService class there is a private method that checks the input received from UI according to a regex.

The positive test I wrote is working fine:

@Test
public void testEmailPatroonCorrect() throws Exception{

    //Correcte emails
    List<String> emails = new ArrayList<>();
    emails.add("user@domain.com");
    emails.add("user@domain.co.in");
    emails.add("user.name@domain.com");
    emails.add("user_name@domain.com");
    emails.add("username@yahoo.corporate.in");

    Class<AccountService> foo = AccountService.class;
    Method method = foo.getDeclaredMethod("checkEmailPatroon", String.class);
    method.setAccessible(true);

    assertThatCode(() -> {
        for(String email : emails){
            method.invoke(AccountService,email);
        }}).doesNotThrowAnyException();

}

However for the negative test (a list with wrong email patterns) even with only one object in the list for simplicity

@Test
public void testEmailPatroonFout() throws Exception{

    //Verkeerde emailpatronen
    List<String> emails = new ArrayList<>();
    emails.add(".username@yahoo.com");

    Class<AccountService> foo = AccountService.class;
    Method method = foo.getDeclaredMethod("checkEmailPatroon", String.class);
    method.setAccessible(true);

    assertThatThrownBy(()->{
        for(String email : emails){
            method.invoke(AccountService,email);
        }
    }).isInstanceOf(ApplicationException.class).hasMessage(ApplicationExceptionType.ONGELDIGE_EMAIL.getMsg());

}

The exception thrown during test is: java.lang.reflect.InvocationTargetException. In the application the ApplicationException gets caught just fine. Question is how can I write a proper test for a list of wrong email patterns? (without using @VisibleForTesting functionality since it's a school project).

Many thanks!

Aucun commentaire:

Enregistrer un commentaire