For an integration test, I need to mock a specific method in a java service client without destroying the rest of the information in it. It has no self-constructor, so a solution like this is out of the question:
private DBClient mockClient = new DBClient(alreadyExistingClient){
@Override
void deleteItem(Item i){
//my stuff goes here
}
};
Is there a way to mock the deleteItem method such that the credentials, endpoints, etc... are preserved in an existing DBClient object?
edit: mockito is not available for use in this case
You could go lo-fi and create a sub-class of the DBClient class. To this subclass, pass the instance of DBClient you want to mock.
Use composition inside the sub-class, and delegate all method calls to the original DBClient, all except the one you want to mock. Add your mock implementation to the method you want.
This is not as reusable as a mocking framework, but should work.
Hope this helps.
In Mockito 2+ you can use spy feature for this purpose:
Output:
You can use a Dynamic Proxy to intercept any method invocation you want, so you can decide between invoking the real method or do whatever you want instead.
This is an example of how to intercept the method
Set.add()
, you can do exactly the same fordeleteItem()