【问题标题】:Mocking config values when testing a class using spring使用 spring 测试类时模拟配置值
【发布时间】:2011-08-11 10:29:11
【问题描述】:

我正在尝试测试类似的课程

@Controller
public class FailureController {

    @Value("#{configValues.defaultRedirectUrl}")
    private String defaultRedirectUrl;
public FailureController (String defaultRedirectUrl) {
this.defaultRedirectUrl = defaultRedirectUrl;
}
...

问题是如果不为测试类创建一个特殊的构造函数(如上),我无法测试这个类,它最终是在FailureController 中初始化defaultRedirectUrl。

在测试期间如何在不创建构造函数(来自 Spring 上下文)的情况下对其进行测试。我的主要目标是在运行测试时在没有构造函数的情况下初始化 FailureController 中的值。

是否有可能在测试期间以某种方式加载 spring 上下文并初始化 FailureController 中的字段 这就是我一直在做的,但它不起作用,defaultRedirectUrl 仍然是 null 在 FailureController 中。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext-test.xml" })
public class FailureControllerTest {
    @Autowired
    FailureController failureController;

applicationContext-test.xml

...
        <bean id="failureController" class="se.synergica.watchtower.controllers.FailureController">
        </bean>

        <import resource="spring-config-test.xml" />
    </beans>

谢谢。 人

【问题讨论】:

    标签: spring junit mocking config


    【解决方案1】:

    我会在您的测试类路径(标准项目中的 src/test/resources)中创建一个单独的 applicationContext.xml 文件。在那里我会设置一个带有虚拟值的 configValues 对象。 您的被测类也应该在该上下文中实例化。

    然后在 junit 测试中像这样加载测试上下文:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("/applicationContext-test.xml")
    public class MyTest {
    
        @Autowired
        private AClassToBeTest subject;
    
        //...perform test on subject
    }
    

    更多关于弹簧测试:http://static.springsource.org/spring/docs/3.0.x/reference/testing.html

    【讨论】:

    • 谢谢你,我想,我对你的理解不够好...... AClassToBeTest 中的 theUrl 字段会被初始化吗?我想它不会。 @ContextConfiguration 不是仅用于加载测试的上下文,即 AClassToBeTestTest,而不是正在测试的类,即 AClassToBeTest?我稍微编辑了我的问题。
    • 重点是您已经通过测试应用程序上下文实例化了 AClassToBeTest。所以AClassToBeTest应该定义在applicationContext-test.xml中。您将该实例注入到您的单元测试中,它应该像在正常运行时一样被初始化。与运行时的唯一区别是您使用不同的 spring 上下文,您可以在其中为测试值或类似的东西加载不同的属性文件。
    • 由于某种原因,它不起作用。你能帮我吗?我编辑了这个问题。
    【解决方案2】:

    这些配置属性通常来自 .properties 文件 - 只需在单元测试类路径中使用不同的属性文件(带有测试值)

    【讨论】:

    • 通过使用属性文件,是否会初始化被测类中的字段。以及我的测试如何识别其他答案中的属性文件,@ContextConfiguration 正在用于此(尽管这对我不起作用)。
    • @ContextConfiguration 是关于 xml 文件的,它又会加载一个属性文件(通常)以从外部位置获取属性
    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多