Mockito在简单测试中抛出OutOfMemoryError
我尝试使用Mockito模拟数据库池(仅用于检索数据),但是在运行性能测试以在一段时间内检索到许多模拟连接时,它用尽了内存.
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.
这是一个简化的自包含代码,在我的计算机上进行了大约150,000次循环迭代后,该代码引发OutOfMemoryError(尽管似乎没有全局保存任何内容,并且所有内容都应该是可垃圾回收的).我在做什么错了?
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();
}
}
问题在于,模拟对象会记住每个调用的详细信息,以防您稍后希望对其进行验证.最终,它将不可避免地耗尽内存.您需要做的是偶尔使用Mockito.reset
静态方法重置模拟,然后再次对您的方法进行存根.不幸的是,如果不重置存根,就无法清除模拟的验证信息.
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.
有关此问题的详细信息,请参见 https://code.google.com/p/mockito/issues/detail?id = 84
This issue is covered in detail at https://code.google.com/p/mockito/issues/detail?id=84