我有以下Spring Boot应用程序(使用Eureka和Feign):
@SpringBootApplication
@EnableFeignClients
@EnableRabbit
@EnableDiscoveryClient
@EnableTransactionManagement(proxyTargetClass = true)
public class EventServiceApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(EventServiceApplication.class, args);
}
}
和以下测试,用@SpringJpaTest注释:
@RunWith(SpringRunner.class)
@DataJpaTest(showSql = true)
public class EventRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private EventRepository repository;
@Test
public void testPersist() {
this.entityManager.persist(new PhoneCall());
List<Event> list = this.repository.findAll();
assertEquals(1, list.size());
}
}
运行测试时收到以下错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.netflix.discovery.EurekaClient] found for dependency [com.netflix.discovery.EurekaClient]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
完整的堆栈跟踪here
有没有办法解决这个问题?我已经看到它是由@EnableFeignClients和@EnableDiscoveryClient注释引起的。
最后,我设法通过以下方式解决了我的问题:
eureka:
client:
enabled: false
spring:
cloud:
discovery:
enabled: false
config:
enabled: false
@ContextConfiguration(classes = EventServiceApplicationTest.class)
其中EventServiceApplicationTest是:
@SpringBootApplication
@EnableTransactionManagement(proxyTargetClass = true)
public class EventServiceApplicationTest {}
我不知道是否有最简单的方法,但这是有效的。
我和@EnableDiscoveryClient有类似的问题。
我认为在这种情况下,最简单的方法是禁用信息:
eureka:
client:
enabled: false
在src/test/resources/application.[properties|yml]
。然后在运行测试期间,此配置的优先级高于src/main/resources/application.[properties|yml]
。
由于我假设您只打算测试您的存储库层,您可以从与Feign相关的ApplicationContext
中过滤掉不需要的bean等。
您可以通过excludeFilters
的@DataJpaTest
属性配置排除过滤器。
过滤器的详细信息可以在Spring Reference Manual中找到。
另一种选择是禁用Feign等的自动配置 - 在这种情况下你可能会发现这个答案很有用:Disable security for unit tests with spring boot
最简单的方法是在测试类中添加以下配置:
@RunWith(SpringRunner.class)
@TestPropertySource(properties={"eureka.client.enabled=false"})
@DataJpaTest(showSql = true)
public class BankRepositoryTest {
}