gpt4 book ai didi

java - Hibernate 域对象 'not null' 字段 - 如果对象内的字段为空,模拟测试应抛出错误

转载 作者:行者123 更新时间:2023-12-01 10:48:23 25 4
gpt4 key购买 nike

有一个具有“not null”字段的 Hibernate 域对象,该字段具有注释 @Column(nullable=false),这是一个将该对象保存在数据库中的 DAO 类方法。

我正在使用 PowerMockito 来模拟创建 DAO 调用,模拟调用工作正常,但如果我为字段传递 null,模拟测试不会抛出该字段为 null 的错误。

下面是代码、工具/技术(java、spring、hibernate、sqlserver、junits、powermockit)。与 spring 上下文和 hibernate session 配置相关的代码更改很少被省略。

public class Entity{
private String id;
@Column(nullable=false)
private String field;
//setters and getters goes here
}

public class HibernateDAO{
private SessionFactory sessionFactory;

public void create(Entity entity){
getSession().save(entity);
}

public void setSessionFactory(SessionFactory sf){
sessionFactory = sf;
}
}

public class HibernateDAOTest{
HibernateDAO hibernateDAO = new HibernateDAO();
public SessionFactory mockedSessionFactory;
public Session mockedSession;
public Query query;
public SQLQuery sqlQuery;
public Transaction mockedTransaction;
@Before
public void setup() {
mockedSessionFactory = PowerMockito.mock(SessionFactory.class);
mockedSession = PowerMockito.mock(Session.class);
mockedTransaction = PowerMockito.mock(Transaction.class);
query = PowerMockito.mock(Query.class);
sqlQuery = PowerMockito.mock(SQLQuery.class);

PowerMockito.when(mockedSessionFactory.openSession()).thenReturn(mockedSession);
PowerMockito.when(mockedSessionFactory.getCurrentSession()).thenReturn(mockedSession);
PowerMockito.when(mockedSession.beginTransaction()).thenReturn(mockedTransaction);
}

@Test
public void testCreate(){
Entity entityToSave = new Entity();
entityToSave.setId("123");
entityToSave.setField(null);
hibernateDAO.setSessionFactory(mockedSessionFactory);
hibernateDAO.create(entityToSave);//this call should throw error that "field" is null but its not.
}
}

最佳答案

实际上,您的 DAO 中并未完成验证(不可为空检查)。您确实将字段声明为非空,但随后您的create(Entity实体) 方法调用:

    getSession().save(entity);

这就是它的全部作用。现在,验证将在通过 HibernateSession 进行的保存中进行,但所有这些类都被模拟。因此他们不会执行任何验证。

一般来说,这是一个很好的规则,每次您不小心模拟了您测试的同一事物时,您都会退后一步并重新评估:

Did I write that code? Why do I want to test it?

在这种情况下,答案可能是,您应该相信 Hibernate 会处理好事情。如果你想测试你的模型定义,你需要设置一个完整的 Hibernate 上下文并在 Hibernate 不被模拟的情况下执行真正的测试。

关于java - Hibernate 域对象 'not null' 字段 - 如果对象内的字段为空,模拟测试应抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com