Tuesday, April 06, 2010

How to pass system properties to "maven test" task?

Unit test should by definition be very self-contained; and this includes their configuration. But there are cases where it is convenient to either allow overriding such default settings, or run other types of configurable tests (esp. integration) tests as JUnit or TestNG tests. And one straight-forward way to pass configuration is by using Java system properties.

Defining system properties is simple enough: just add "-DpropertyName=value" on command line. But with Maven these will not automatically get propagated (at least not with Surefire plugin, default plugin used for "test" goal. This was apparently done to prevent accidental leakage of system properties that wrapper might otherwise pass (especially environment settings that might vary between environments). At any rate, you have to do some extra work to pass system properties to be accessible by unit test.

Although what seems to be recommend way is to use <systemPropertyVariables> tag (see this page), there is actually an easier way (as suggested by this StackOverflow answer): pass system property "argLine" to Maven, which will then pass the whole value as additional command line argument when test plugin forks JVM. Something like:

  mvn test -DargLine="-Dsystem.test.property=test"

Without doing this, you would basically have to explicitly pass each and every system property using something like:

  <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
  <systemPropertyVariables>
<propertyName>sys.prop.name</propertyName>
<buildDirectory>${sys.prop.name}</buildDirectory>
[...]
  </systemPropertyVariables>
</configuration>
  </plugin>

which is just a whole lot of monkey code, best done without.

On a related note, this somewhat complete list of Maven(-recognized) system properties is a nice resource too.

blog comments powered by Disqus

Sponsored By


Related Blogs

(by Author (topics))

Powered By

About me

  • I am known as Cowtowncoder
  • Contact me at@yahoo.com
Check my profile to learn more.