Java – mockito throws an outofmemoryerror in a simple test
I try to use mockito to simulate the database pool (only for retrieving data), but it will run out of memory when running the performance test that retrieves many simulated connections over a period of time
This is a simplified self-contained code that throws outofmemoryerror after about 150000 loop iterations on my machine (although it seems that nothing can be saved globally and everything should be garbage collectable) What on earth did I do 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(); } }
Solution
The problem is that mock objects are remembering the details of each call in case you want to validate later Eventually, it will inevitably run out of memory All you need to do is reset the simulation occasionally, using mockito Reset the static method and stub your method again Unfortunately, the simulated validation information cannot be cleared without resetting the stub
This problem is in https://code.google.com/p/mockito/issues/detail?id=84 Detailed in