【发布时间】:2020-03-26 06:16:32
【问题描述】:
所以我正在使用模拟数据库层测试 AccountService 类。 在这个 AccountService 类中,有一个私有方法可以根据正则表达式检查从 UI 接收到的输入。
我写的阳性测试工作正常:
@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();
}
但是,对于否定测试(包含错误电子邮件模式的列表),即使为简单起见,列表中只有一个对象
@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());
}
测试时抛出的异常是:java.lang.reflect.InvocationTargetException。在应用程序中,ApplicationException 被很好地捕获。 问题是如何为错误的电子邮件模式列表编写适当的测试? (不使用@VisibleForTesting 功能,因为它是一个学校项目)。
非常感谢!
【问题讨论】:
标签: java testing junit reflection private