0

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?

philabreu
  • 55
  • 1
  • 7

1 Answers1

1

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, 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:

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

}
ujulu
  • 3,289
  • 2
  • 11
  • 14
  • 1
    It did not work @ujulu manager keeps giving nullPointerException; I've actually been researching the web, and I've seen that it's much more effective to do an integration test because these test the transmission and data traffic from one component to another, which would be my situation. Anyway, thanks for the help. – philabreu Nov 28 '17 at 11:28
  • "manager keeps giving nullPointerException: " on which line do you get the exception? Edit the question and post the code for `ClientesRepository` as well as for `Cliente`. Then I'll try to see where you're experiencing a problem. – ujulu Nov 28 '17 at 17:32