Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to Spring tests

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

like image 493
user1052610 Avatar asked May 09 '26 07:05

user1052610


1 Answers

I don't think this is possible, not because of Spring, see this other question on SO with an explanation:

  • Passing JUnit command line parameters in eclipse

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.

like image 74
Andrei Stefan Avatar answered May 12 '26 06:05

Andrei Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!