其他分享
首页 > 其他分享> > 将参数传递给Spring测试

将参数传递给Spring测试

作者:互联网

我们有一个标准的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,请参阅SO上的this其他问题并进行解释.
如果您决定在Eclipse中使用JVM参数(-Dkey =值格式),那么在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参数).

标签:spring-test,junit4,spring
来源: https://codeday.me/bug/20191121/2051714.html