Mock and inject a service class at the same time

Asked

Viewed 49 times

-1

I have a spring test class that in some cases I want it to behave in the normal flow, that is, when it is done a findAll() hitting the repository it returns the value it selects from the embedded database, in another flow within the same test method, I want when findAll() to return a mocked value. I need it to be done that way because I want to simulate two concurrent processes and test a specific business flow. I used an example of what the mock would be like, but that way it doesn’t work.

Example:

Class Test{

  @Autowired
  private Service service;

  @Autowired
  private Repository repository;

  @Test
  public void teste(){
    service.metodo();
    when(repository.findAll()).thenReturn(null);
    service.metodo();
  }


}

class Service{

 @Autowired
 private Repository repository;

 public void metodo(){

   Entity x  =  repository.findAll();
   ....

 }

}

1 answer

0

If you use @Autowired you will not mock the values, you will follow the normal flow, in case you search for data in the database. You have to use @Injectmocks and @Mock

Browser other questions tagged

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