We use Coverity to identify potential security and quality flaws in our Java code. In one of our unit tests, we have some testing that involves database connection code:
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
when(connection.createStatement()).thenReturn(statement);
Coverity complains about a potential resource leak:
CID 21920: Resource leak (RESOURCE_LEAK)4. leaked_resource: Failing to save or close resource created by connection.createStatement()
My understanding of how Mockito works is that connection.getStatement()
is never actually called, and so no statement is being created that needs to be closed later. (This is in contrast to the typical case in databases where a JDBC connection would need to be closed.)
Is my understanding correct? Is it fair to say that this is a false report from Coverity, caused by the atypical behavior of getConnection()
in the context of mocking? If not, please straighten me out.
I'd say your understanding isn't quite correct.
In your code, connection.createStatement()
does get called, but it doesn't get called on a 'real' connection that will create a resource on a database somewhere. The mock Connection
implementation that Mockito creates just tracks that the method has been called, and returns null
. Later, when the thenReturn()
method is called, Mockito can link the call to createStatement()
with the value passed to thenReturn()
so that the mock Connection
can return the mock Statement
when the createStatement()
method is called on it.
Ultimately, this is a false positive report from Coverity: there is no resource leak issue here. However, there is the question of the value of running a scanner such as Coverity on test code. In particular, I'm not sure how you could have a security flaw in test code, given that it isn't interactive and isn't something that you either ship to customers or upload to a server somewhere.