I have configuration file:
@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();
}
}
And configuration for tests:
@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();
}
}
My repository uses one of that beans:
private final File usersDatabase;
@Autowired
public UserRepositoryImpl(@Qualifier("usersDatabase") File usersDatabase) {
this.usersDatabase = usersDatabase;
}
My repostitory tests file:
@SpringBootTest
@Import(TestConfig.class)
public class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
// tests here
}
At the result my main program works properly, but tests fail with followi message in the end:
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.io.File' available: expected single matching bean but found 2: getUsersDatabaseTestFile,getUsersDatabaseFile
I have found the problem:
@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 ?
CodePudding user response:
You can use a combination of @Profile
and @ActiveProfiles
to load only the desired classes for your tests. See prototype below.
Configuration
@Configuration
@Profile("test")
public class TestOnlyConfigs {
// define beans
}
Test
@ActiveProfiles("test")
public class Tests {
// write tests
}
References