关于使用存根 - Java

发布于 2024-11-04 03:28:57 字数 413 浏览 3 评论 0原文

我正在阅读 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲影 2024-11-11 03:28:57

存根和真实类都应该实现某个接口,即ITimeProvider,并且setTimeProvider() 应该将此接口作为其参数。该接口必须公开 SUT 需要与对象交互的所有方法,因为 TimeDisplay 现在只能通过 ITimeProvider 接口使用该对象(这允许我们使用存根而不是我们测试中的真实物体)。

在示例中,SUT (TimeDisplay) 似乎只需要 getTime() 方法,因此接口应该只包含该方法:

public interface ITimeProvider {
    Calendar getTime();
}

存根的声明应该是

public class TimeProviderTestStub implements ITimeProvider { ... }

并且真实类的声明应该是

public class TimeProvider implements ITimeProvider { ... }

最后,SUT 必须更改其 setter 方法以接受接口:

public void setTimeProvider(ITimeProvider timeProvider) { ... }

并将其内部 timeProvider 字段更改为 ITimeProvider 类型。

如果您不控制真实类的代码(因此无法使其实现接口),则可以创建一个适配器类来包装真实类并实现该接口。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文