Skip to content

Instantly share code, notes, and snippets.

@kiru
Created July 6, 2017 11:20
Show Gist options
  • Save kiru/b87a1d42c720966f8fe0b9b99a4bedd6 to your computer and use it in GitHub Desktop.
Save kiru/b87a1d42c720966f8fe0b9b99a4bedd6 to your computer and use it in GitHub Desktop.
TestNG Issue 1461 Junit example
import org.junit.Test;
import org.junit.runner.Computer;
import org.junit.runner.JUnitCore;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
public class MemoryLeakNotPresentInJUnit {
@RunWith(Suite.class)
@Suite.SuiteClasses({ MyTestClassWithGlobalReferenceCounter.class })
public class AllTests {
}
public static void main(String[] args) throws InterruptedException {
// we run the test programmatically
runTest();
// lets wait for garbage collection
waitForAllObjectsDestructed();
}
public static void waitForAllObjectsDestructed() throws InterruptedException {
while (true) {
System.out.println("waiting for clean up...");
// enforce a full gc
System.gc();
// check if there are still instances of our test class
if (MyTestClassWithGlobalReferenceCounter.currentNumberOfMyTestObjects == 0) {
// if we reach this point, all test instances are gone,
// ... however this never happens ...
break;
}
// let's wait 5 seconds and try again ...
Thread.sleep(1000);
System.out.println("["+MyTestClassWithGlobalReferenceCounter.currentNumberOfMyTestObjects+"] test object(s) still exist.");
}
}
private static void runTest() {
Computer computer = new Computer();
JUnitCore jUnitCore = new JUnitCore(){
@Override
protected void finalize() throws Throwable {
// it seems that this object will never be finalized !!!
System.out.println("TestNG finalized");
}
};
jUnitCore.run(computer, AllTests.class);
}
/**
* we create a test NG class here, which has a global counter, counting all instances.
*/
public static class MyTestClassWithGlobalReferenceCounter {
/**
* global counter that keeps track on how many objects are currently on the heap
*/
public static int currentNumberOfMyTestObjects = 0;
public MyTestClassWithGlobalReferenceCounter() {
System.out.println("constructor");
// increase the counter
++currentNumberOfMyTestObjects;
}
@Test
public void aTestMethod1() {
System.out.println("test method 1");
}
@Test
public void aTestMethod2() {
System.out.println("test method 2");
}
@Override
protected void finalize() throws Throwable {
System.out.println("finalize");
// this will be called when this object is removed from the heap
--currentNumberOfMyTestObjects;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment