java.lang.Assertionerror: Expected: not null but: was null - Junit test

Asked

Viewed 324 times

0

The variable result is returning NULL although the Object is filled.

This is my test;

@RunWith(MockitoJUnitRunner.class)
public class IndicioDAOTest {

    @Mock
    private IndicioDAO indicioDAO;

    @Test
    public void findByIdIndicio() {

        IndicioEntity entity = criarIndicioEntity();

        IndicioEntity result = indicioDAO.getPorId(entity.getCodigo());

        assertThat(result, notNullValue());

    }

    private IndicioEntity criarIndicioEntity() {

        TipoIndicioEntity tipoIndicio = new TipoIndicioEntity();
        tipoIndicio.setCodigo(1);

        NaturezaIndicioEntity naturezaIndicio = new NaturezaIndicioEntity();
        naturezaIndicio.setCodigo(1);

        SituacaoIndicioEntity situacaoIndicio = new SituacaoIndicioEntity();
        situacaoIndicio.setCodigo(1);

        PessoaJuridicaPublicaEntity pessoaJuridicaPublicaEntity = new PessoaJuridicaPublicaEntity();

        pessoaJuridicaPublicaEntity.setCodigo(1);

        IndicioEntity entity = new IndicioEntity();
        entity.setCodigo(1);
        entity.setTipoIndicio(tipoIndicio);
        entity.setUnidadeJurisdicionada(pessoaJuridicaPublicaEntity);
        entity.setCodigoNaturezaIndicio(naturezaIndicio.getCodigo());
        entity.setCpfServidor("80445500700");
        entity.setDescricao("qualquer valor dentro");
        entity.setValor(1500.0);
        entity.setPrazo(15);
        entity.setSituacaoAtual(situacaoIndicio);
        entity.setDataUltimaMovimentacao(getDataAtual());
        return entity;
    }

}

Note the image of a debug execution;

inserir a descrição da imagem aqui

But my object is filled;

inserir a descrição da imagem aqui

I need help fixing the bug!

1 answer

1


You’re calling a method of indicioDAO, which is a @Mock.

The standard behavior of a @Mock will always return null, it is a utility object for checks and simulation of returns, exceptions, among other things.

In short, you always tell the mock what to do.

So to return some value, you should use it this way:

Mockito.when(indicioDAO.getPorId(entity.getCodigo())).thenReturn(entity);

When the call comes getPorId, passing the entity code, will be returned to the entity.

This would solve your problem, but I don’t believe this is a valid test, and you are explicitly saying what the DAO will return, and check if the returned value is the value you ordered the mock to return.

  • You’re right, the test passed, but how could I check if the returned value is the value I sent to the mock?

  • I’ve seen it, you don’t have to.... Thank you very much anyway.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.