Both the stub and the real class are supposed to implement some interface, i.e. ITimeProvider
, and setTimeProvider()
should take this interface as its parameter. The interface must expose all methods that the SUT needs to interact with the object, since TimeDisplay
can now only use the object through the ITimeProvider
interface (which allows us to use a stub instead of the real object in our tests).
In the example, the SUT (TimeDisplay
) seems to only need the getTime()
method, so the interface should only contain that method:
public interface ITimeProvider {
Calendar getTime();
}
The declaration of the stub should be
public class TimeProviderTestStub implements ITimeProvider { ... }
and the declaration of the real class should be
public class TimeProvider implements ITimeProvider { ... }
Finally, the SUT must change its setter method to accept the interface:
public void setTimeProvider(ITimeProvider timeProvider) { ... }
and also change its internal timeProvider
field to be of the type ITimeProvider
.
If you do not control the code of the real class (so that you cannot make it implement the interface), you can create an adapter class which wraps the real class and implements the interface.