Mockito throws OutOfMemoryError on a simple test

I tried to use Mockito to simulate a database pool (only for retrieving data), but when I ran a performance test that for a while took a lot of connections to the layouts, it ran out of memory.

Here is the simplified self-contained code that throws OutOfMemoryError after about 150,000 loop iterations on my machine (despite the fact that nothing is saved around the world and everything should be garbage collection). 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(); } } 
+6
source share
3 answers

The problem is that the mock object remembers the details of each call if you want to check it later. In the end, it will inevitably end. What you need to do is sometimes reset the layout using the static Mockito.reset method and drown your method again. Unfortunately, there is no way to clear the error control information without also restarting the installation.

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

+12
source

David-wallace's answer explains why you encounter OOM: a mock object remembers the details of each call.

But no less important question: what now to do? In addition to what David has already proposed, the latest versions of Mockito 1.10.19, as well as the upcoming 2.0.x versions now support the so-called stubOnly mocks (see javadoc ):

stubOnly: The stub layout does not record method calls, thereby saving memory but not allowing call verification.

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 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()); 
+12
source

This did not cause an OutOfMemory error, so I can only assume that you need to increase the amount of heap available when it starts. Here is how you can do it.

+1
source

Source: https://habr.com/ru/post/948597/


All Articles