我使用 qaf 和 testng 来运行黄瓜测试用例。现在我想在测试步骤中使用 spring 来自动装配 UserRepository。
<suite name="Web Demo Suite" verbose="0" parallel="tests" thread-count="100">
<listeners>
<listener class-name="com.quantum.listeners.QuantumReportiumListener" />
</listeners>
<test name="Web Test" enabled="true" thread-count="10">
<groups>
<run>
<include name="@testH2Spring"/>
</run>
</groups>
<classes>
<class name="com.qmetry.qaf.automation.step.client.gherkin.GherkinScenarioFactory" />
</classes>
</test>
</suite>
以下是功能文件:
@testH2Spring
Scenario: H2 Spring test
When I control with DB by Spring
以下是 JPA 配置:
@Configuration
@EnableJpaRepositories(basePackages = "com.quantum.repository")
public class H2DBConfig {
@Bean
public ComboPooledDataSource datasource() throws PropertyVetoException {
String path = System.getProperty("user.dir");
System.out.println(path);
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("org.h2.Driver");
dataSource.setJdbcUrl("jdbc:h2:file:" + path + "/src/main/resources/data/test");
dataSource.setUser("sa");
dataSource.setPassword("");
dataSource.setInitialPoolSize(5);
dataSource.setMaxPoolSize(10);
return dataSource;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.H2);
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
adapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");
return adapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter){
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactoryBean.setPackagesToScan("com.quantum.entity");
return entityManagerFactoryBean;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
@Bean
public BeanPostProcessor persistenceTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
下面是用户存储库
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {}
下面是测试步骤:
@QAFTestStepProvider
@ContextConfiguration(classes = H2DBConfig.class)
public class WebTestSteps extends AbstractTestNGSpringContextTests {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@When("^I open browser to web page$")
public void iOpenBrowserToWebPage() {
User user = userRepository.getOne(1);
System.out.println(user.toString());
}
}
如果我使用 testng xml 像上面那样运行黄瓜测试用例,则 UserRepository 无法成功@Autowired。
如何解决它以便 UserRepository 可以@Autowired?