向Spring测试传递参数

3
我们有一个标准的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测试时,需要添加哪些代码以确保从IDE(在我们的情况下是Eclipse)传递程序参数(例如--key=value)到应用程序上下文中?谢谢。
1个回答

4

我认为这不可能,不是因为Spring的问题,可以参考 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),而不是程序参数

在Eclipse中,可以通过右键单击测试类 -> 运行为 -> 运行配置 -> JUnit -> 参数选项卡 -> VM参数进行访问。


我认为这个问题在于,虽然它允许测试程序使用“-D”传递变量,但它们不会被加载到Spring上下文中。 - user1052610
不起作用。Spring测试的第一件事是加载app-context.xml文件。然后,Spring将抛出IllegalStateException异常,因为${}占位符变量中的一个未被定义。因此,在测试本身中使用@Value声明变量本身并没有帮助。 - user1052610
很奇怪。对我来说可以运行。我已经更新了我的答案并提供了另一个代码示例。 - Andrei Stefan
谢谢Andrei。问题在于我使用了“程序参数”而不是VM参数传递参数。 - user1052610

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接