Passing arguments to Spring tests
-
21-12-2019 - |
Pregunta
We have a standard Spring test class which loads an application context:
@ContextConfiguration(locations = {"classpath:app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTest {
...
}
The XML context uses standard placeholders e.g.: ${key}
When the full application is run normally (not as a test), the main class will load the application context as follows so that the command line arguments are seen by Spring :
PropertySource ps = new SimpleCommandLinePropertySource(args);
context.getEnvironment().getPropertySources().addLast(ps);
context.load("classpath:META-INF/app-context.xml");
context.refresh();
context.start();
When running the Spring test, what code needs to be added to ensure that program arguments (e.g. --key=value
): are passed from the IDE (in our case Eclipse) into the application context?
Thanks
Solución
I don't think this is possible, not because of Spring, see this other question on SO with an explanation.
If you decide to use JVM arguments (-Dkey=value
format) in Eclipse instead, it's easy in Spring to use those values:
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;
...
}
Or, without @Value
and just using a property placeholder:
@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());
}
}
where test-app-context.xml
is
<bean class="com.foo.bar.ExampleService">
<property name="arg" value="${arg1}" />
</bean>
<context:property-placeholder />
and ExampleService
is:
@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;
}
}
and the argument passed to the test is a VM argument (specified like -Darg1=value1
) and not a Program argument (both in Eclipse accessed with Right-Click on the test class -> Run As -> Run Configurations -> JUnit -> Arguments tab -> VM Arguments).