I believe we have a very common question, but searching docs and web
does not help.
We have some of tests that must be run only if developer really wants
it. Because they involve test DB which may be absent, and it is not
considered as test failures. Also, the developer must be sure he is
not using production DB in test config.properties.
What is the best practice to do this?
For example, I'd like to call ">mvn test -Dtest.db=true" to enable
these dangerous tests.
One way to do this is to use a Method Selector. Method Selectors are
called for each TestNG configuration and test method. In your
IMethodSelector implementation, you can inspect a custom test method
annotation (or some other indicator) to determine whether or not you
want to run it. Here's some sample code for includeMethod() which
uses a @RequiresTestDB custom annotation:
public boolean includeMethod( IMethodSelectorContext
methodSelectorContext,
ITestNGMethod testNGMethod,
boolean isTestMethod )
{
if ( !isTestMethod )
{
return true;
}
boolean shouldInclude = true;
Method method = testNGMethod.getMethod();
if ( method.getAnnotation( RequiresTestDB.class ) != null &&
System.getProperty( "test.db" ) != null )
{
shouldInclude = false;
methodSelectorContext.setStopped( true );
}
return shouldInclude;
}
When running TestNG, you specify one or more Method Selector classes
and a corresponding priority. Set your Method Selector to a negative
number if you want it to be called before TestNG's default Method
Selectors.
-John