Raja Subramani Raja Subramani - 1 month ago 14
Java Question

How to get runtime values through (Maven, TestNG, Java)

I am just started to automate my Web service project with Java. I need to run it in Jenkins so I built the project with TestNG framework and Maven. I am able to run some automated test suite with Jenkins without any issues.

Now I have problem like, I need to get the user input at runtime (say HostName, UserName, Password, etc) and then the test suite should run accordingly.

The problem I am facing like, while entering the input in the console the cursor is not returning back to the program and it simple going to ideal state.

PFA screenshots:

Test case running as Maven build

Test case running as TestNG

Answer

Making your tests interactive is absolutely bad approach - the build is just not reproducible at all, makes other people know what parameters are expected and so on.

If your test case need to take parameters at runtime (or more accurately, they need to be set before maven build is started) you have several options.

Option #1. Properties file and maven resource processing.

Idea is just to have a properties file in your project and tell maven to resolve variable values there. Example:

Pom.xml:

<resources>
  <resource>
    <directory>src/test/resources/data</directory>
    <filtering>true</filtering>
  </resource>
</resources>

/src/test/resources/data/myproperties.properties:

myVar = ${myVar}

Then run maven build as:

mvn -DmyVar=value clean install

You can use not only properties files, but any other file types (for example XML).

Hint: you can use maven-enforcer-plugin to force user to enter -DmyVar, this plugin will fail the build if all required properties are not set.

Option #2. Properties file and Spring DI.

Idea is almost same as above, but Spring is used to inject all necessary stuff to test class. Something like:

@Component
public class MyTest
{
   @Value(${myProperty})
   private String myValue;

   // ... Test methods which can use myValue ...
}

See this answer for full example of possible Spring configuration.

Btw, your test is the a unit test, but integration test - in case if it involves deploying of your web service or something else like this. Therefore, it would be wise to split unit tests (maven-surefire-plugin) and integration tests (maven-failsafe-plugin).

Comments