我的问题是如何测试这个'删除'方法?我无法为Message对象添加ID,因为它是生成的值。所以我也不能使用findbyID(整数id)方法..任何帮助将不胜感激谢谢!
我的测试
@Test
public void testDelete(){
System.out.println("delete");
Message message = new Message();
// message.setID(1) -> This is not allowed
message.setSubject("Subject");
message.setContent("Content");
messageDAO.register(message);
int count = messageDAO.getCount();
assertEquals("Check if the message has been persisted into db", 1, count);
messageDAO.delete(1); //returns null
count = messageDAO.getCount();
assertEquals("Check if the message has been deleted from db", 0, count);
}
DAO:
@Transactional
public void register(Message message) {
em.persist(message);
}
@Transactional
public void delete(Integer id) {
Message m = getMessageById(id);
em.remove(em.merge(m));
}
@Transactional
public Message getMessageById(Integer id){
return em.find(Message.class, id);
}
@Transactional
public int getCount() {
Query query = em.createNativeQuery("select count(*) from messages");
int count = ((BigInteger) query.getSingleResult()).intValue();
return count;
}
答案 0 :(得分:0)
您可以尝试以下方法: