@RefreshScope seems to ignore Mockito's mocks

后端 未结 1 1344
忘了有多久
忘了有多久 2021-01-28 06:52

I\'m implementing a service using Spring Boot and Spring Cloud Config service to provide the configuration values. In my Service I have a couple of config values which need to r

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 07:40

    When adding the @RefreshScope the bean becomes a proxy instead of an actual raw implementation. Currently the RestTemplate is set on the proxy rather then the underlying instance. (If you debug you would see that your MyServiceImpl is actually more like an instance of MyServiceImpl$SpringCgLib#353234).

    To fix you need to manually set the dependency using ReflectionTestUtils and AopTestUtils. The latter is to obtain the actual proxy.

    Remove the @InjectMocks annotation and add the following to your setup method after the initialization of the mocks:

    Object actualTarget = AopTestUtils.getUltimateTargetObject(service);
    ReflectionTestUtils.setfield(actualTarget, "restTemplate", restTemplate);
    

    For versions earlier as 4.2 the following might do the trick

    Object actualTarget = (service instanceof Advised) ? ((Advised) service).getTargetSource().getTarget() : service;
    

    The problem is that Mockito doesn't detect the proxy and just sets the field. The ReflectionTestUtils doesn't detect the proxy either hence the manual unwrapping. I actually stepped into this trap a couple of times before, which led me to create SPR-14050 this morning to have it embedded in the ReflectionTestUtils to easy the pain a little.

    0 讨论(0)
提交回复
热议问题