简体   繁体   中英

How to mock object in EntityManager?

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?

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?

The reason is that you tell the manager to return you a mock object, ie, 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:

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());

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM