Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On TestNG using new JVM thread/instance for each test

Tags:

java

testng

I'm running tests on a legacy system that has many static objects and uses several singletons... i'm not able to detect them all, so this leads to errors when running my test suite.

I'm using eclipse, testng and Mockito. To run the test we we use eclipse run configurations and/or gradle build.

Issue:

  • when i run my tests as single test (Run as -> TestNG test) it's working properly (it's ok, its' working)
  • when i use my suite.xml file the tests fail because some singletons/static variables still are mocked/have the wrong content/are wrong initialized

how can i create a new JVM for each test?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="Test p1t1">
        <classes>
            <class name="package1.Test1"/> <!-- test ok -->
        </classes>
    </test>
    <test name="Test p1t2">
        <classes>
            <class name="package1.Test2"/> <!-- will fail now -->
        </classes>
    </test>             
</suite> 

when i swap my execution order the problem occurs on the other side:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="Test p1t2">
        <classes>
            <class name="package1.Test2"/> <!-- test now ok -->
        </classes>
    </test>
    <test name="Test p1t1">
        <classes>
            <class name="package1.Test1"/> <!-- will fail now instead -->
        </classes>
    </test>             
</suite> 
like image 916
Martin Frank Avatar asked Nov 15 '25 09:11

Martin Frank


1 Answers

You can use the Maven Surefire Plugin and set reuseForks to "false":

Indicates if forked VMs can be reused. If set to "false", a new VM is forked for each test class to be executed. If set to "true", up to forkCount VMs will be forked and then reused to execute all tests.

e.g.:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <reuseForks>false</reuseForks>
        <includes>
            <include>**/Test*.java</include>
        </includes>
    </configuration>
</plugin>

See Maven Surefire Plugin – Fork Options and Parallel Test Execution for more details.

like image 126
mfulton26 Avatar answered Nov 18 '25 04:11

mfulton26