java测试中模拟的好例子是什么?
java中是否有EntityManager模拟的好例子java测试中模拟的好例子是什么?,java,testing,mocking,Java,Testing,Mocking,java中是否有EntityManager模拟的好例子 提前感谢这是您的BookingController的一部分: public double totalPerAccount(Account account) { Double total = em.createNamedQuery("Booking.totalPerAccount", Double.class) .setParameter("ACCOUNT", account)
提前感谢这是您的BookingController的一部分:
public double totalPerAccount(Account account) {
Double total = em.createNamedQuery("Booking.totalPerAccount", Double.class)
.setParameter("ACCOUNT", account)
.getSingleResult();
if(total == null)
return 0.0;
else
return total;
}
以下是模拟EntityManager的单元测试的两个示例:
@Test
public void t012Mock(){
BookingController controller = new BookingController();
controller.em = mock(EntityManager.class);
TypedQuery mockedQuery = mock(TypedQuery.class);
when(controller.em.createNamedQuery("Booking.totalPerAccount",Double.class)).thenReturn(mockedQuery);
when(mockedQuery.setParameter(anyString(), any())).thenReturn(mockedQuery);
//getSingleResult should return null to test if its converted to 0....
when(mockedQuery.getSingleResult()).thenReturn(null);
double d = controller.totalPerAccount(new Account(0L,"Hallo")); //<-It doesn't matter which account
//Check if the correct Methods are called
verify(controller.em).createNamedQuery("Booking.totalPerAccount",Double.class);
verify(mockedQuery).setParameter(anyString(), any());
verify(mockedQuery).getSingleResult();
//Methods should be called exactly once
verify(mockedQuery,times(1)).getSingleResult();
//if the query against the db returns null 0.0 should be returned.
assertThat(0.0, is(d));
}
@Test
public void t013Mock(){
BookingController controller = new BookingController();
controller.em = mock(EntityManager.class);
TypedQuery mockedQuery = mock(TypedQuery.class);
//This is the statement i am looking for
when(controller.em.createQuery("select b from Booking b", Booking.class)).thenReturn(mockedQuery);
//return empty list...
when(mockedQuery.getResultList()).thenReturn(new LinkedList<Booking>());
//Call method ignore return value
controller.findAll();
//verify that getResultList was called...
verify(mockedQuery).getResultList();
//Check that getResultList was called exactly once
verify(mockedQuery,times(1)).getResultList();
}
@测试
公众假期{
BookingController=新的BookingController();
controller.em=mock(EntityManager.class);
TypedQuery mockedQuery=mock(TypedQuery.class);
当(controller.em.createNamedQuery(“Booking.totalPerAccount”,Double.class)),然后返回(mockedQuery);
当(mockedQuery.setParameter(anyString(),any())。然后返回(mockedQuery);
//如果将其转换为0,则getSingleResult应返回null以进行测试。。。。
when(mockedQuery.getSingleResult())。然后返回(null);
double d=controller.totalPerAccount(新帐户(0L,“你好”);//请提供更多详细信息,或许我可以提供更多信息。