3

I have the following powermock test:

@RunWith(PowerMockRunner.class)
@PrepareForTest({DaoCaseTypeDefinition.class, QDataContext.class})
public class PowermockTest {

private static QDataContext m_dc;
private static DaoCaseTypeDefinition m_daoCaseTypeDefinition;

@Test
public void test() throws Exception {
  m_dc = mock(QDataContext.class);
  m_daoCaseTypeDefinition = mock(DaoCaseTypeDefinition.class);
  when(m_daoCaseTypeDefinition.findAll(m_dc))
    .thenReturn(Collections.EMPTY_LIST);

  DaoCaseTypeDefinition daoCaseTypeDefinition = new DaoCaseTypeDefinition();
  List<CaseTypeDefinition> all = daoCaseTypeDefinition.findAll(m_dc);

  System.out.println("sleep");
  Thread.sleep(2000);
}

@AfterClass
public static void after() throws InterruptedException {
  m_daoCaseTypeDefinition = null;
  m_dc = null;
  System.out.println("done");
  Thread.sleep(2000);
}
}

In this test I am using PowerMockito 1.7.1 on jdk1.8 (also used PowerMockito 2 btw). When I let Intellij run this test over and over again and attaching VisualVM to it, it becomes clear that I have a memory leak.

visualvm memory leak by powermockito

I noticed that for every testclass annotated with PowerMockRunner.class a MockClassloader instance is created that is holding the references to, in this case a DaoCaseTypeDefinition. Unfortunately the mockclassloader instances are never recovered.

Is there something in my test that I'm doing wrong? Why is the garbage collection not clearing the mockclassloader instances?

Vladimir Shefer
  • 661
  • 3
  • 19
mmelsen
  • 636
  • 1
  • 8
  • 24

2 Answers2

3

Although I did not find a solution for this problem, but I did find a workaround.

I'm using Maven and this allows me to create a new jvm proces by configuring forking. This way, based on the configuration I can instruct when to kill a jvm process used for running the powermock unittests.

This way the memory leaks will not result in out of memories. See Fork Options and Parallel Test Execution

Vladimir Shefer
  • 661
  • 3
  • 19
mmelsen
  • 636
  • 1
  • 8
  • 24
1

There is a related open issue in the PowerMockito for this.

https://github.com/powermock/powermock/issues/227

tuk
  • 5,941
  • 14
  • 79
  • 162