开发者

About use Stubs - Java

开发者 https://www.devze.com 2023-03-01 23:50 出处:网络
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 Time

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消