Mockito with Nativequery

Asked

Viewed 77 times

0

need to test a method that uses Native query. However on line

Query q = em.createNativeQuery(strQuery, Projeto.class);

No value is assigned to q and it is null. Can someone help me?

It follows the method I want to test (which is in the Projectoserviceimpl class) :

@Override
public  Page<Projeto> buscaAtestadosComFiltro(String[] filtros, PageRequest pageRequest) {
    String strQuery = montaQueryAtestadoComFiltro(filtros);
    Query q = em.createNativeQuery(strQuery, Projeto.class);
    Page<Projeto> result = new PageImpl<Projeto>(q.getResultList());
    return result;
}

and my test class:

@SpringBootTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class ProjetoServiceImplTest {

  Projeto projeto1;

  @Mock
  private EntityManager manager;

  @InjectMocks
  private ProjetoServiceImpl projImpl = new ProjetoServiceImpl();

  @Before
  public void setup() {
    projeto1 = new Projeto();
    projeto1.setId(1L);
 }

 @Test
public void testaBuscaAtestadosComFiltro() {
    List<Projeto> projetos = new ArrayList<Projeto>();
    projetos.add(projeto1);

    Query query = mock(Query.class);

    Mockito.when(manager.createNativeQuery("java",Projeto.class)).thenReturn(query);
    Mockito.when(query.getResultList()).thenReturn(projetos);

    String[] filtros = new String[] {"java"};
    PageRequest pageRequest = new PageRequest(0, 12,Direction.valueOf("DESC"), "id");

    Page<Projeto> result = projImpl.buscaAtestadosComFiltro(filtros, pageRequest);
    assertNotNull(result);

}
  • Have you tried manager.createNativeQuery(Mockito.anyString(),Mockito.any(Projeto.class))?

  • He doesn’t even accept the second argument

  • So Have you tried manager.createNativeQuery(Mockito.anyString(), Projeto.class)?

No answers

Browser other questions tagged

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