Question

I'm readin http://xunitpatterns.com/Test%20Stub.html and have some questions about the use of stubs, for example, in the code shown on the page the author creates a class called TimeProviderTestStub.java for use in test code. I have some doubts about this line in the test code:

TimeDisplay sut = new TimeDisplay();
  //      Test Double installation
  sut.setTimeProvider(tpStub);

Do I need modify my class(SUT) to recieve one object TimeProviderTestSub?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top