我正在学习Spring Core认证,对在JUnit测试中使用配置概要文件(profiles)有一些疑问。
我知道如果我将一个类注释如下:
@Profile("stub")
@Repository
public class StubAccountRepository implements AccountRepository {
private Logger logger = Logger.getLogger(StubAccountRepository.class);
private Map<String, Account> accountsByCreditCard = new HashMap<String, Account>();
/**
* Creates a single test account with two beneficiaries. Also logs creation
* so we know which repository we are using.
*/
public StubAccountRepository() {
logger.info("Creating " + getClass().getSimpleName());
Account account = new Account("123456789", "Keith and Keri Donald");
account.addBeneficiary("Annabelle", Percentage.valueOf("50%"));
account.addBeneficiary("Corgan", Percentage.valueOf("50%"));
accountsByCreditCard.put("1234123412341234", account);
}
public Account findByCreditCard(String creditCardNumber) {
Account account = accountsByCreditCard.get(creditCardNumber);
if (account == null) {
throw new EmptyResultDataAccessException(1);
}
return account;
}
public void updateBeneficiaries(Account account) {
// nothing to do, everything is in memory
}
}
我正在声明一个属于“stub”配置文件的服务bean。
因此,如果我的测试类像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=TestInfrastructureConfig.class)
@ActiveProfiles("stub")
public class RewardNetworkTests {
.....................................
.....................................
.....................................
}
这意味着将使用属于 stub 配置文件的 Bean,以及那些没有配置文件的 Bean。是这样吗?还是我漏掉了什么?
如果我在一个 Java 配置类 上使用 @ActiveProfiles 注解,会发生什么?
像这样:
@Configuration
@Profile("jdbc-dev")
public class TestInfrastructureDevConfig {
/**
* Creates an in-memory "rewards" database populated
* with test data for fast testing
*/
@Bean
public DataSource dataSource(){
return
(new EmbeddedDatabaseBuilder())
.addScript("classpath:rewards/testdb/schema.sql")
.addScript("classpath:rewards/testdb/test-data.sql")
.build();
}
}
我应该做什么?我认为在这个类中配置的所有bean都将属于jdbc-dev配置文件,但我不确定。你能给我更多关于这件事的信息吗?
为什么我必须在一个**配置类**上使用@Profile注解,而不是直接注解我的bean?
Tnx