mardi 9 octobre 2018

How to throw an error inside a private method inside a service with Mockito

I have an issue trying to make some automated tests : I have a service (spring). This service is providing a public method, used for a process. This process is made of 3 underlaying processes. Those processes are in private methods, and are calling some other services.

I want to test the behavior when one of those 3 private process is throwing an error. I figured out that Mockito could help me. However I can't make it work. As my three methods are private and I can't use PowerMock, I tried using when().thenThrow on the public methods in the other service, which is called by my private method.

I got various results, NullPointerException, process working without any throw/error, dependencies issues etc.

My code looks like :

 @Test
public void test() throws Throwable {
    Mockito.when(SecondServiceCalledByPrivateMethod.publicMethod(Mockito.any(), Mockito.any()))
            .thenThrow(new Exception("failed!!!"));
    request lRequest = createRequest(myObjects);

    FirstService.executeProcess(lRequest);
}

With a config class :

@Configuration

public class ConfigClass{

@Bean
@Primary
public SecondService secondService() {
    return Mockito.mock(SecondService.class);
}

}

Inside services, I have multiple @Autowired etc. I don't know if it matters. It's the first time I try to use Mockito. Do you have any idea how to make it works or what I am missing ?

Aucun commentaire:

Enregistrer un commentaire