向Spring测试传递参数

brjng4g3  于 2023-04-10  发布在  Spring
关注(0)|答案(1)|浏览(67)

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

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

XML上下文使用标准占位符,例如:${key}当完整的应用程序正常运行时(不是作为测试),main类将加载应用程序上下文,如下所示,以便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)传递到应用程序上下文中的吗?
谢谢

64jmpszr

64jmpszr1#

我不认为这是可能的,不是因为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 argument(像-Darg1=value1一样指定),不是Program argument
在Eclipse中,都可以通过 * 右键单击 * 测试类-〉Run As-〉Run Configurations-〉JUnit-〉Arguments选项卡-〉VM Arguments来访问。

相关问题