Reputation: 23633
For testing purposes, I want to replace the implementation of a few methods of an object that implements some interface. One way of doing this would be to create a new object, passing the instance as a parameter to the constructor, and manually recreating all of the methods to use the instance's methods for all but a couple of methods, which would be overridden for testing purposes. Unfortunately, the interface has a large number of methods, which makes this option tedious.
Is there some way to create an object that is a "subclass of an instance of an object" in the sense that it simply calls the instance's method's for all calls except when overridden?
Upvotes: 0
Views: 261
Reputation: 16226
Dynamic Proxy Classes may be a way to go. I have never used it before, however it is a viable mechanism to catch every method invocation and decide whether to invoke old method or do something else and/or extra.
The link I provided has even an example of DebugProxy
which may be helpful for you.
Upvotes: 3
Reputation: 1778
Create a mock using some mocking framework like Mockito:
MyComplexInterface mock = Mockito.mock(MyComplexInterface.class);
Mockito.when(mock.someMethod()).thenReturn("some value");
Mockito are able to mock both interfaces and concrete classes.
Upvotes: 4
Reputation: 38521
For testing purposes, I want to replace the implementation of a few methods of an object that implements some interface.
Simply create a class that extends the current concrete class, and override only those methods from the interface you want to test.
public class ForTest extends X {
@Override
public void m1() {
.
.
.
}
}
public class X implements Z{
//all the overrides
}
interface Z {
//lots of methods
}
Upvotes: 1