Mockito在简单测试中抛出OutOfMemoryError [英] Mockito throws an OutOfMemoryError on a simple test

查看:158
本文介绍了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

这篇关于Mockito在简单测试中抛出OutOfMemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆