【问题标题】:Where to instantiate context.xml in Test Environment在测试环境中实例化 context.xml 的位置
【发布时间】:2014-05-24 17:15:59
【问题描述】:

我们在 Java 项目中使用 Spring Framework (XML Version) 4.0.5.RELAASEE。 在我们的应用程序中,context.xml 在应用程序启动时被实例化,并通过依赖注入提供每个属性。

现在我想知道在测试环境中在何处实例化它的最佳(和常用)策略是什么。 (我们有一些单元、集成和系统测试,它们至少需要 context.xml 中提供的 databaseBaseConnector bean,)

我考虑过创建一个抽象类,每个测试都从中扩展,但在这种情况下,它将在每次测试之前重新实例化。我想有一个类似于主应用程序的解决方案,其中上下文只实例化一次,其他所有需要的东西都是通过依赖注入设置的。

研究这个话题还没有太大帮助,所以我决定问这个问题。

【问题讨论】:

  • spring 为内置的 junit 提供了 SpringJUnit4ClassRunner 框架。您只需直接在 junit 本身中配置应用程序上下文。您可以查看它以获取更多详细信息

标签: java spring unit-testing testing


【解决方案1】:

Spring 带有 SpringJUnit4ClassRunner@ContextConfiguration -注解。如果你使用它们,那么 spring 将在不同的测试中重用相同的 Spring Context。

所以一个 Spring 测试类可以如下所示:

package com.queomedia;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
//@Transactional
@ContextConfiguration(SpringTestContext.APPLICATION)
public class SpringContextTest {

    @Autowire
    private ApplicationContext applicationContext;

    //Test that the spring context can been loaded
    @Test
    public void testSpringContextLoad() {
        Assert.assertNotNull("application context expected", this.applicationContext);
    }
}

【讨论】:

  • 你的意思可能是“@Autowired”,你知道为什么我不能解析 SpringTestContext 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多