I have the following code:
try {
em.persist(myObject);
em.flush();
}
catch (Exception e) {
System.out.println("An Exception occur when trying to persist and flush");
}
In test I have mock my EntityManager with Mockito:
@Mock
EntityManager mockEm;
but as persist and flush are void methods, I'm not able able to write something like:
when(mockEm.persist(anObject).then(doSomeThing);
How can I write unit testing (with JUnit)to mock em.persist and em.flush in order to test both cases with and without exception? Thanks.
I guess we need more details. For now, you can do something like this: (it's kind of pseudo-code).
@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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.