【问题标题】:Autoconfigure ReactiveCrudRepos in integration tests在集成测试中自动配置 ReactiveCrudRepos
【发布时间】:2020-09-10 19:54:46
【问题描述】:

我在编写一些集成测试时遇到了一些困难。我有类似的东西

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Service.class)
public class ServiceTest {
    @Rule
    public PostgreSQLContainer postgres = new PostgreSQLContainer();

    @Autowired
    Service Service;

    @Before
    public void setUp() {
        PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
                .host(postgres.getHost())
                .port(postgres.getFirstMappedPort())  // optional, defaults to 5432
                .username(postgres.getUsername())
                .password(postgres.getPassword())
                .database(postgres.getDatabaseName())  // optional
                .build());

        Resource resource = new ClassPathResource("sql.sql");

        Mono<PostgresqlConnection> mono = connectionFactory.create();
        mono.map(connection -> connection
                .createStatement(Helpers.asString(resource))
                .execute()).block();

    }

    @Test
    public void test() {
        Request Request = new Request();
        request.setName("name");
        Mono<Item> itemMono = Service.createNewHub(hubRequest);
        Item item = itemMono.block();

        Assert.assertEquals(1L, 1L);

    }
}

我的 Service.class 如下所示

@Service
public class Service {

    private Repository repository;

    public Service(Repository repository) {
        this.repository = repository;
    }

    public Flux<Item> getAllItems() {
            return repository.findAll();
    }
}

还有我的回购

@Repository
public interface Repository extends ReactiveCrudRepository<Item, Integer>  {

}

我的错误如下

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.Repository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

虽然我在应用程序中编写的所有代码都可以正常注入,但对于 ReactiveCrudRepos,我在获取它们的实例化对象方面没有任何运气。我需要做什么才能创建和注入实现?

【问题讨论】:

    标签: spring-boot spring-webflux spring-test


    【解决方案1】:

    只要您使用@SpringBootTest(classes = Service.class),其他bean 就不会加载到应用程序上下文中。注解的注解元素class描述为:

    用于加载ApplicationContext组件类

    删除元素并按原样使用@SpringBootApplication

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Service.class)
    public class ServiceTest { /* code */ }
    

    请记住,使用这种方式测试的应用程序上下文与将在生产环境中运行的应用程序上下文完全不同。这应该是最后的手段。


    此外,当存在Spring注解@Repository本身时,避免将接口命名为Repository。我个人更喜欢:

    @Repository
    public interface ItemRepository extends ReactiveCrudRepository<Item, Integer>  {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-09-29
      • 2021-06-14
      • 1970-01-01
      • 2018-08-04
      • 2016-10-10
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多