关于使用存根 - Java
我正在阅读 http://xunitpatterns.com/Test%20Stub.html 并有一些问题关于存根的使用,例如,在页面上显示的代码中,作者创建了一个名为 TimeProviderTestStub.java
的类以在测试代码中使用。我对测试代码中的这一行有一些疑问:
TimeDisplay sut = new TimeDisplay();
// Test Double installation
sut.setTimeProvider(tpStub);
我是否需要修改我的类(SUT)以接收一个对象 TimeProviderTestSub?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
存根和真实类都应该实现某个接口,即
ITimeProvider
,并且setTimeProvider()
应该将此接口作为其参数。该接口必须公开 SUT 需要与对象交互的所有方法,因为TimeDisplay
现在只能通过ITimeProvider
接口使用该对象(这允许我们使用存根而不是我们测试中的真实物体)。在示例中,SUT (
TimeDisplay
) 似乎只需要getTime()
方法,因此接口应该只包含该方法:存根的声明应该是
并且真实类的声明应该是
最后,SUT 必须更改其 setter 方法以接受接口:
并将其内部
timeProvider
字段更改为ITimeProvider
类型。如果您不控制真实类的代码(因此无法使其实现接口),则可以创建一个适配器类来包装真实类并实现该接口。
Both the stub and the real class are supposed to implement some interface, i.e.
ITimeProvider
, andsetTimeProvider()
should take this interface as its parameter. The interface must expose all methods that the SUT needs to interact with the object, sinceTimeDisplay
can now only use the object through theITimeProvider
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 thegetTime()
method, so the interface should only contain that method:The declaration of the stub should be
and the declaration of the real class should be
Finally, the SUT must change its setter method to accept the interface:
and also change its internal
timeProvider
field to be of the typeITimeProvider
.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.