【问题标题】:Passing arguments to Spring tests将参数传递给 Spring 测试
【发布时间】:2014-07-31 09:45:07
【问题描述】:

我们有一个标准的 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)传递到应用程序上下文中?

谢谢

【问题讨论】:

    标签: spring junit4 spring-test


    【解决方案1】:

    我认为这是不可能的,不是因为 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)而不是 Program 参数(两者都在 Eclipse 中通过右键单击访问测试类 -> 运行方式 -> 运行配置 -> JUnit -> 参数选项卡 -> VM 参数)。

    【讨论】:

    • 我认为的问题是,虽然它允许测试程序使用 -D 获取传递的变量,但它们不会被加载到 Spring 上下文中。
    • 不起作用。 Spring 测试要做的第一件事是加载 app-context.xml。然后 Spring 将抛出 IllegalStateException,因为 ${} 占位符变量之一尚未定义。因此,使用 @Value 在测试本身中声明变量本身并没有帮助。
    • 这很奇怪。为我工作。我已经用另一个代码示例更新了我的答案。
    • 谢谢安德烈。问题是我使用“程序参数”而不是 VM 参数传入 args
    猜你喜欢
    • 2021-05-25
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多