如何为持久和刷新异常编写单元测试
How can I write Unit Test for persist and flush exceptions
我有以下代码:
try {
em.persist(myObject);
em.flush();
}
catch (Exception e) {
System.out.println("An Exception occur when trying to persist and flush");
}
在测试中,我用 Mockito 模拟了我的 EntityManager:
@Mock
EntityManager mockEm;
但是由于 persist 和 flush 是无效的方法,我无法编写如下内容:
when(mockEm.persist(anObject).then(doSomeThing);
我如何编写单元测试(使用 JUnit)来模拟 em.persist 和 em.flush,以便在有无异常的情况下测试这两种情况?
谢谢
我想我们需要更多细节。现在,您可以这样做:(这是一种伪代码)。
@Test // it passess when there's one object in repository (I assume u have clean memory db)
public void shouldPersistMyObject() throws Exception {
em.persist(myObject);
em.flush();
Assert.assertThat(dao.findAll(), Matchers.equalTo(1));
}
@Test(expected = <YourDesiredException>.class) // if <YourDesiredException> is thrown, your test passes
public void shouldThrowExceptionWhenSavingCorruptedData() {
//set NULL on some @NotNull value, then save, like:
myObject.setUserId(null);
em.save(myObject); //exception is thrown
}
我有以下代码:
try {
em.persist(myObject);
em.flush();
}
catch (Exception e) {
System.out.println("An Exception occur when trying to persist and flush");
}
在测试中,我用 Mockito 模拟了我的 EntityManager:
@Mock
EntityManager mockEm;
但是由于 persist 和 flush 是无效的方法,我无法编写如下内容:
when(mockEm.persist(anObject).then(doSomeThing);
我如何编写单元测试(使用 JUnit)来模拟 em.persist 和 em.flush,以便在有无异常的情况下测试这两种情况? 谢谢
我想我们需要更多细节。现在,您可以这样做:(这是一种伪代码)。
@Test // it passess when there's one object in repository (I assume u have clean memory db)
public void shouldPersistMyObject() throws Exception {
em.persist(myObject);
em.flush();
Assert.assertThat(dao.findAll(), Matchers.equalTo(1));
}
@Test(expected = <YourDesiredException>.class) // if <YourDesiredException> is thrown, your test passes
public void shouldThrowExceptionWhenSavingCorruptedData() {
//set NULL on some @NotNull value, then save, like:
myObject.setUserId(null);
em.save(myObject); //exception is thrown
}