将参数传递给Spring测试

时间:2014-07-31 09:45:08

标签: spring junit4 spring-test

我们有一个标准的Spring测试类,用于加载应用程序上下文:

@ContextConfiguration(locations = {"classpath:app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTest {
   ...
}

XML上下文使用标准占位符,例如:${key}当完整应用程序正常运行(而不是作为测试)时,主类将按如下方式加载应用程序上下文,以便Spring可以看到命令行参数:

PropertySource ps = new SimpleCommandLinePropertySource(args);
context.getEnvironment().getPropertySources().addLast(ps);
context.load("classpath:META-INF/app-context.xml");
context.refresh();
context.start();

运行Spring测试时,需要添加哪些代码以确保程序参数(例如--key=value):从IDE(在我们的例子中是Eclipse)中传递到应用程序上下文中?

由于

1 个答案:

答案 0 :(得分:3)

我不认为这是可能的,不是因为Spring,请参阅this关于SO的其他问题并给出解释。 如果您决定在Eclipse中使用JVM参数(-Dkey=value格式),那么在Spring中使用这些值很容易:

import org.springframework.beans.factory.annotation.Value;

@ContextConfiguration(locations = {"classpath:app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTest {

    @Value("#{systemProperties[key]}")
    private String argument1;

    ...

}

或者,没有@Value并只使用属性占位符:

@ContextConfiguration(locations = {"classpath:META-INF/spring/test-app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class ExampleConfigurationTests {

    @Autowired
    private Service service;

    @Test
    public void testSimpleProperties() throws Exception {
        System.out.println(service.getMessage());
    }

}

其中test-app-context.xml

<bean class="com.foo.bar.ExampleService">
    <property name="arg" value="${arg1}" />
</bean>

<context:property-placeholder />

ExampleService是:

@Component
public class ExampleService implements Service {

    private String arg;

    public String getArg() {
        return arg;
    }

    public void setArg(String arg) {
        this.arg = arg;
    }

    public String getMessage() {
        return arg; 
    }
}

并且传递给测试的参数是 VM参数(指定为-Darg1=value1)而不是程序参数(在使用Right访问的Eclipse中都是单击测试类 - &gt;运行方式 - &gt;运行配置 - &gt; JUnit - &gt;参数选项卡 - &gt; VM参数)。

相关问题