So, I have a class I need to mock, since I don't want the tests to actually do this connection, I want to provide fake results for the privateMethodCall()
:
public final Connection {
private Connection() {
//does some stuff
}
public static void get(/*some params*/) {
Connection conn = new Connection();
con.privateMethodCall();
}
}
The issue is most singletons I see mocked are returning the instance in the public static method, this one is not.
In the class I'm testing, the Connection class is just called in a private method from the method I'm trying to test (prepareForThing()
).
import Connection;
public class ManagerClass {
ManagerClass(/* some params*/){
//Does some stuff
}
void prepareForThing(/* params */) {
// Does stuff
doThing();
}
private void doThing(/* more params */) {
// Does some stuff
Connection.get();
// Continues doing stuff
}
}
Even if I create another constructor and pass the mock class like is suggested Using Singleton with Interfaces Java, since the instance is just created and used within the static method it wouldn't work.
My workaround so far is to pass a boolean isTest
to the class I'm testing, and then modify the Connection
class so it can be extended, write a ConnectionMock
, and if the isTest
is set to true, modify the call. But this makes the ManagerClass
depend on a test class, ConnectionMock
, which is not good
But I don't know if there might be a better workaround with mockito or something. I would like the mock to be available for other tests, rather than create it for the test only. And I'm not sure extending this class is the best approach, but I can't create an interface because all methods in Connection
are private or static. Any ideas?