如何在EntityManager中模拟对象? [英] How to mock object in EntityManager?
问题描述
我有这个课程来模拟DAO:
I have this class to mock a DAO:
//...
private ClientesRepository clientesRepository;
@Mock
private Cliente cliente;
@Mock
private EntityManager manager;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
manager = Mockito.mock(EntityManager.class);
clientesRepository = new ClientesRepository(manager);
}
@Test
public void testBuscarPorId() {
Mockito.when(manager.find(Cliente.class, new Long(1))).thenReturn(cliente);
Cliente clientePesquisado = clientesRepository.buscarPorId(new Long(1));
assertEquals(Long.valueOf(1), clientePesquisado.getId());
}
但是我要嘲笑的对象管理器只是为空...我该如何解决呢?
But just the object manager I'm mocking just comes null ... how can I solve this?
推荐答案
假定您的DAO针对给定ID返回类型为Cliente
的对象,则可能是以下原因. (我猜是因为您尚未发布方法clientesRepository.buscarPorId()
的代码).
Assuming your DAO is returning an object of type Cliente
for a given ID, the following might be the reason. (I am guessing because you haven't posted the code for the method clientesRepository.buscarPorId()
).
但是我要嘲笑的对象管理器只是为空...我该如何解决呢?
But just the object manager I'm mocking just comes null ... how can I solve this?
原因是您告诉manager
返回一个模拟对象,即cliente
.对于返回对象的方法,默认情况下,该对象将返回null
值.这意味着clientePesquisado.getId()
将返回null
,因为Long
是一个对象.以下是Mockito
文档的摘录:
The reason is that you tell the manager
to return you a mock object, i.e., cliente
. And this object will return you null
value by default for methods returning objects. This means clientePesquisado.getId()
will return null
because Long
is an object. Here is an extract from Mockito
documentation:
默认情况下,对于所有返回值的方法,模拟将根据需要返回null,原始/原始包装器值或空集合.例如,对于int/Integer为0,对于boolean/Boolean为false.
By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.
因此,您必须将测试方法更改为以下内容:
So you have to change your test method to something like the following:
//...
private ClientesRepository clientesRepository;
@Mock
private EntityManager manager;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
clientesRepository = new ClientesRepository(manager);
}
@Test
public void testBuscarPorId() {
Cliente expected = new Cliente(1, ...);
Mockito.when(manager.find(Cliente.class, new Long(1))).thenReturn(expected);
Cliente clientePesquisado = clientesRepository.buscarPorId(new Long(1));
assertEquals(Long.valueOf(1), clientePesquisado.getId());
}
这篇关于如何在EntityManager中模拟对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!