[英]unit testing a DAO method using mocked entity manager get issue when testing Exception
我有一个简单的DAO方法正在尝试测试:
public boolean insertUser (User user) throws DaoException {
boolean result = false;
try {
em.persist(user);
result = true;
} catch ( Exception e) {
throw new DaoException( e );
}
return result;
}
作为持久化可以返回一个异常,我想对这种情况进行单元测试:
我嘲笑实体管理器:
@Mock
EntityManager mockEm;
而我的测试:
@Test
public void testExceptionEntityExistInsertUser() throws Exception {
System.out.println("entity already exist exception");
boolean result;
when(mockEm.persist(user)).thenThrow(EntityExistsException.class);
result = userDao.insertUser(user);
}
但是在线when(mockEm.persist(user))。thenThrow(EntityExistsException.class); 我遇到以下错误:此处不允许使用“无效”类型
我不明白问题的出处。
解决方案是设置不允许的实体数据。 例如,当此数据具有@NotNull标记时,该数据为null:
@Test
public void testExceptionEntityExistInsertUser() throws Exception {
System.out.println("entity already exist exception");
boolean result;
user.setData(null) // assuming data has a NotNull tag
result = userDao.insertUser(user);
}
然后测试将生成一个异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.