Strategy for unit testing a Spring Cloud Service

浪尽此生 提交于 2019-11-30 04:34:25

1, first create config bean, let the discovery client and feignclient only work when "eureka.enabled" is true

@Configuration
@EnableDiscoveryClient
@EnableFeignClients
@ConditionalOnProperty(name = "eureka.enabled")
public class EurekaConfig {
}

2, disable the eureka config for test profile, so in application-test.yml

eureka:
     enabled: false

3, my project is build by maven, so i create a implement for my feign client interface, for example:

@Service
public class DataServiceImpl implements DataService {}

after this, when you run test in unit test with

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest({"server.port=0", "management.port=0",    "spring.profiles.active=test"})
public abstract class AbstractIntegrationTests {}

the fake service will inject in to spring context.

Or for normal unit test case, you can just need mockito mock the service class and use set method or construct method inject the mock object in your class

My first attempt crashed because of another bug... So it works fine with a @Configuration annotated class Conf which creates an fake implementation of DataClient like this:

@Bean
@Primary
public DataClient getDataClient() {
    ...
}

Added to my test via

@SpringApplicationConfiguration(classes = {Application.class, Conf.class})

the tested service instance uses the fake implementation correctly.

Adding on Yunlong's answer on annotating on a separate configuration class.

If the configuration class is placed under a different package than the root package, you will need to specify the "basePackages" for the @EnableFeignClients to scan for the annotated @FeignClient component.

com.feign.client.FeignClient.class

@FeignClient(value = "${xxxx}")
public interface FeignClient {
}

com.feign.config.EurekaConfig.class

@Configuration
@EnableFeignClients(basePackages = {"com.feign.client"})
@EnableEurekaClient
@ConditionalOnProperty(name = "eureka.enabled")
public class EurekaClientConfig {
}

Ps. I couldnt comment to the original reply so I created a new answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!