Mockito throws an OutOfMemoryError on a simple test

こ雲淡風輕ζ 提交于 2019-12-21 12:31:14

问题


I tried using Mockito to simulate a database pool (for retrieving data only), but when running a performance test that retrieved many mock connections over a period of time, it ran out of memory.

Here is a simplified self-contained code, which throws an OutOfMemoryError after about 150,000 loop iterations on my machine (despite that nothing seems to be saved globally, and everything should be garbage collectable). What am I doing wrong?

import static org.mockito.Mockito.when;

import java.sql.Connection;

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class Test1 {

    static class DbPool {
        public Connection getConnection() {return null;}
    }

    @Mock
    private DbPool dbPool;

    @Mock
    private Connection connection;

    public Test1() {
        MockitoAnnotations.initMocks(this);
        when(dbPool.getConnection()).thenReturn(connection);

        for(int i=0;i<1000000;i++) {
            dbPool.getConnection();
            System.out.println(i);
        }
    }

    public static void main(String s[]) {       
        new Test1();
    }
}

回答1:


The problem is that the mock object is remembering details of every invocation, in case you wish to verify it later. Eventually, it will inevitably run out of memory. What you need to do is occasionally reset the mock, using the Mockito.reset static method, and stub your method again. Unfortunately, there is no way to clear out a mock's verification information without also resetting the stubbing.

This issue is covered in detail at https://code.google.com/p/mockito/issues/detail?id=84




回答2:


The response by david-wallace explains why you run into an OOM: a mock object is remembering details of every invocation.

But an equally important question is: now what to do about it? In addition to what David already suggested, the latest Mockito versions 1.10.19 as well as upcoming 2.0.x now support so-called stubOnly mocks (see javadoc):

stubOnly: A stub-only mock does not record method invocations, thus saving memory but disallowing verification of invocations.

Scala usage example:

import org.mockito.Mockito
val list = Mockito.mock(classOf[Foo], Mockito.withSettings().stubOnly())

// The syntax is a bit more concise when using ScalaTest's MockitoSugar
val foo = mock[Foo](Mockito.withSettings().stubOnly())

Java usage example (untested):

import org.mockito.Mockito;
Foo mock = Mockito.mock(Foo.class, Mockito.withSettings().stubOnly());



回答3:


This did not throw an OutOfMemory error for me so I can only assume you need to increase the amount of heapspace available when you run it. Here's how you can do that.



来源:https://stackoverflow.com/questions/17437660/mockito-throws-an-outofmemoryerror-on-a-simple-test

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!