使用模拟实体管理器对 DAO 方法进行单元测试在测试异常时出现问题
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;
}
因为坚持可以 return 一个例外我想对这个案例进行单元测试:
我嘲笑过实体管理员:
@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);我有以下错误:
'void'此处不允许输入
我不明白问题出在哪里。
解决方法是设置一个实体数据不允许。例如,当此数据具有@NotNull 标记时,数据为空:
@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);
}
然后测试会产生异常。
我正在尝试测试一个简单的 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;
}
因为坚持可以 return 一个例外我想对这个案例进行单元测试:
我嘲笑过实体管理员:
@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);我有以下错误: 'void'此处不允许输入
我不明白问题出在哪里。
解决方法是设置一个实体数据不允许。例如,当此数据具有@NotNull 标记时,数据为空:
@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);
}
然后测试会产生异常。