我有以下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注释引起的。

最佳答案

最终,我设法通过以下方式解决了我的问题:

  • 添加了具有以下内容的bootstrap.yml:
    eureka:
      client:
        enabled: false
     spring:
       cloud:
         discovery:
           enabled: false
       config:
           enabled: false
    
  • 我编写了一个测试配置,并在测试中引用了它:
    @ContextConfiguration(classes = EventServiceApplicationTest.class)
    

    其中EventServiceApplicationTest为:
    @SpringBootApplication
    @EnableTransactionManagement(proxyTargetClass = true)
    public class EventServiceApplicationTest {}
    

  • 我不知道是否有最简单的方法,但这可行。

    10-07 23:31