Mockito throws an OutOfMemoryError on a simple test
heap-memory, java, mockito
Solution
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
Problem
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(); } } ```