如何在主程序中使用 return String 的两个(或更多)bean,并在测试时用另外两个替换它们?

How can I use two beans (or more) that return String in main program and replace them with another two while testing?

我有配置文件:

@Configuration
public class UrlAnalyzerConfiguration {

    @Bean
    @Qualifier("usersDatabase")
    public File getUsersDatabaseFile() {
        return Paths.get("src/main/resources/database/users.csv").toFile();
    }

    @Bean
    @Qualifier("urlsDatabase")
    public File getUrlsDatabaseFile() {
        return Paths.get("src/main/resources/database/urls.csv").toFile();
    }
}

以及测试配置:

@TestConfiguration
public class TestConfig {

    @Bean
    @Qualifier("usersDatabase")
    public File getUsersDatabaseTestFile() {
        return Paths.get("src/test/resources/database/users.csv").toFile();
    }

    @Bean
    @Qualifier("urlsDatabase")
    public File getUrlsDatabaseTestFile() {
        return Paths.get("src/test/resources/database/urls.csv").toFile();
    }
}

我的存储库使用其中一个 bean:

    private final File usersDatabase;
    
    @Autowired
    public UserRepositoryImpl(@Qualifier("usersDatabase") File usersDatabase) {
        this.usersDatabase = usersDatabase;
    }

我的 repostitory 测试文件:

@SpringBootTest
@Import(TestConfig.class)
public class UserRepositoryTest {
    @Autowired
    private UserRepository userRepository;
    
    // tests here
}

结果我的主程序运行正常,但测试失败,最后出现以下消息:

通过构造函数参数 0 表示的未满足的依赖关系;嵌套异常是 org.springframework.beans.factory.NoUniqueBeanDefinitionException:没有 'java.io.File' 类型的合格 bean 可用:预期单个匹配 bean 但找到 2:getUsersDatabaseTestFile、getUsersDatabaseFile


我发现了问题:

@TestConfiguration class is used in addition to your application’s primary configuration. It means, that tests use @Configuration and @TestConfiguration together! But anyway, how can I use then my beans properly ?

您可以结合使用 @Profile@ActiveProfiles 来为您的测试加载所需的 类。请参阅下面的原型。

配置

@Configuration
@Profile("test")
public class TestOnlyConfigs {
    // define beans
}

测试

@ActiveProfiles("test")
public class Tests {
    // write tests
}

参考资料

  1. @Profile
  2. @ActiveProfiles