Q:

Can I use mockito for partial overriding of existing objects (not just for testing)?

I have a following issue. I have a method that uses an implementation of Connection. That is, the method looks like this:
try (Connection conn = getConnection()) {
  // Do some queries here
}

However, we need to have an exact statistic, how many queries did this method execute, and there are a lot of such methods, that we need to analyze. So here is what I came up with
try (Connection conn = new LogCountConnection(getConnection)) {
  // Do some queries here
}

The LogCountConnection basically passes all it's calls to the standard implementation, but for some methods it increments the counter value, and the close method is overridden like this:
@Override
public void close() throws SQLException {
  log.info(String.format("Number of queries executed: %d", counter));
  conn.close();
}

However, it looks really tedious, that I have to actually create a whole new class there methods look mostly like this:
@Override
public boolean getAutoCommit() throws SQLException {
 return conn.getAutoCommit();
}

This definitely looks like something from AOP, but we are not using in our project AspectJ or something like that. Can I use mockito for partial mocking of methods on existing object for that, or is too risky and should be used only strictly in tests?

A:

As already pointed out in comments, mocking or spying most likely won't solve your problem.
The classical delegation can probably avoided in your use case by implementing dynamic proxies. Intercepting just some methods of Connection interface becomes possible with according branching in InvocationHandler. The article https://jaxenter.de/jdbc-treiber-selbstgebaut-java-trickkiste-636 (unfortunately in German only) outlines a solution to a similar problem as yours.

