1

I have a service with a method that includes a local variable (cliente), a pojo, not a bean, and I would like to mock a method of that object (consultaDatos( ... )) in a test. So the code of my service is like this:

@Service
public class ServicioFn {
    ...
    public RespuestaConsultaFamiliaNumerosa obtenerDatosFamiliaNumerosa( ... ) {
        Cliente cliente = ...;
        return cliente.consultaDatos( ... );
    }
}

As cliente is not a bean, @MockBean in my test (it's a @SpringBootTest) doesn't work. How could I mock that object?

Casti
  • 157
  • 1
  • 14
  • Better: Re-engineer! (Why not spring bean???;) But we can also "hack": ... – xerx593 Dec 22 '21 at 08:49
  • Does this answer your question? [Mocking methods of local scope objects with Mockito](https://stackoverflow.com/questions/6520242/mocking-methods-of-local-scope-objects-with-mockito) – xerx593 Dec 22 '21 at 08:49
  • ...and also possible: not a (classic) "spring bean", but a (spring managed/test interceptable) `@ConfigurationProperties` pojo...see here: [ext config#typesafe](https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties) – xerx593 Dec 22 '21 at 08:56
  • Thanks for the suggestions. I'm trying with powermockito but I can't get it working, and I'm doing it like in that other question, maybe there's some dependency or import that I have wrong, I'm still looking into it. In regards to `@ConfigurationProperties`, I'm not understanding how to set it up correctly (sorry, I'm new to all of this), could you provide a basic example? – Casti Dec 22 '21 at 10:08
  • no, now better understand: cliente is not properties! it *is* should be a bean! – xerx593 Dec 22 '21 at 10:23
  • ..now remains question: What is the appropriate [scope](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes)? (default(, as the service) is: "singleton") – xerx593 Dec 22 '21 at 11:21
  • Why? I mean, the application's logic is as it should be, there's no point in making `cliente` a bean, besides *I can't change the original code*, I'm just writing the tests for this project – Casti Dec 22 '21 at 11:25

0 Answers0