【问题标题】:integration tests - embedded jetty - how to setup data集成测试 - 嵌入式码头 - 如何设置数据
【发布时间】:2014-11-25 18:11:05
【问题描述】:

我想知道您通常如何为集成测试设置数据。

当我的测试开始时,我启动嵌入式码头:

@Before
public void startServer() throws Exception {
    server = new Server(8080);
    server.setStopAtShutdown(true);
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setDescriptor("WEB-INF/embedded-web.xml");
    webAppContext.setContextPath("/core-test");
    webAppContext.setResourceBase("src/main/webapp");  
    webAppContext.setClassLoader(getClass().getClassLoader());
    server.addHandler(webAppContext);
    server.start();
}

在embedded-web.xml中有一个spring应用上下文的引用:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/applicationContext-test.xml</param-value>
</context-param>

在 applicationContext-test.xml 中有一个内存 h2 数据库的配置:

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" />
</bean>

最好的解决方案是将 Spring 服务类自动连接到测试中,然后设置数据库,但我想访问由 jetty 启动的应用程序上下文是不可能的。

【问题讨论】:

    标签: java spring junit integration-testing embedded-jetty


    【解决方案1】:

    我发现有 3 种解决方案可以为集成测试提供数据:

    1. 使用应用上下文启动时正在运行的spring应用监听器

      public class CustomTestInitializer implements ApplicationListener<ContextRefreshedEvent> {
          @Autowired
          CustomService customService;
      
          @Override
          public void onApplicationEvent(ContextRefreshedEvent event) {
            // TODO: implement you loginc
          }
      }
      
    2. 配置实体管理器时可以提供sql导入文件(it-test-init.sql位于src/test/resouces):

      <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
          <property name="jpaProperties">
              <props>
                  <prop key="hibernate.hbm2ddl.auto">create</prop>
                  <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                  <prop key="hibernate.hbm2ddl.import_files">it-test-init.sql</prop>
              </props>
          </property>
      </bean>
      
    3. 您可以使用Arquillian 并在远程服务器(例如 JBoss)上执行测试。当您使用难以在嵌入式服务器(CDI、EJB 等)上运行的 Java EE/容器技术时,强烈建议使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-10
      • 2016-01-14
      • 2013-12-25
      • 2014-03-15
      • 2017-10-20
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多