BDD/TDD:依赖关系可以成为一种行为吗? [英] BDD/TDD: can dependencies be a behavior?

查看:75
本文介绍了BDD/TDD:依赖关系可以成为一种行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我不要使用实现细节.依赖项似乎是实现细节.但是我也可以将其表述为一种行为.

I've been told not to use implementation details. A dependency seems like an implementation detail. However I could phrase it also as a behavior.

示例:LinkList依赖于存储引擎来存储其链接(例如LinkStorageInterface).构造函数需要传递一个已实现的LinkStorageInterface的实例以完成其工作. 我不能说"shouldUseLinkStorage".但也许我可以说"shouldStoreLinksInStorage".

Example: A LinkList depends on a storage engine to store its links (eg LinkStorageInterface). The constructor needs to be passed an instance of an implemented LinkStorageInterface to do its job. I can't say 'shouldUseLinkStorage'. But maybe I can say 'shouldStoreLinksInStorage'.

在这种情况下,测试"的正确之处是什么?我应该测试它在商店中存储链接(行为)还是根本不测试它?

What is correct to 'test' in this case? Should I test that it stores links in a store (behavior) or don't test this at all?

推荐答案

依赖关系本身不是预期的行为,但最肯定的是对依赖关系进行的操作是.您应该测试(调用者)知道的东西,并避免测试需要您对SUT的内部工作有深入了解的东西.

The dependency itself is not an expected behavior, but the actions called on the dependency most certainly are. You should test the stuff you (the caller) know about, and avoid testing the stuff that requires you to have intimate knowledge of the inner workings of the SUT.

稍微扩展一下示例,可以想象我们的LinkStorageInterface具有以下定义(伪代码):

Expanding your example a little, lets imagine that our LinkStorageInterface has the following definition (Pseudo-Code):

Interface LinkStorageInterface

  void WriteListToPersistentMedium(LinkList list)

End Interface

现在,由于您(调用方)正在为该接口提供具体的实现,因此在调用LinkList上的Save()方法时测试WriteListToPersistentMedium()是否被调用是完全合理的.

Now, since you (the caller) are providing the concrete implementation for that interface it is perfectly reasonable for you to test that WriteListToPersistentMedium() gets called when you invoke the Save() method on your LinkList.

再次使用伪代码进行测试,可能看起来像这样:

A test might look like this, again using pseudo-code:

void ShouldSaveLinkListToPersistentMedium()

  define da = new MockLinkListStorage()  
  define list = new LinkList(da)

  list.Save()

  Assert.Method(da.WriteListToPersistentMedium).WasCalledWith(list)

end method

您已经测试了预期的行为,而没有测试SUT或模拟的实现特定细节.您想要避免测试的(主要是)是这样的:

You have tested expected behavior without testing implementation specific details of either your SUT, or your mock. What you want to avoid testing (mostly) are things like:

  1. 调用方法的顺序
  2. 公开一种方法或属性,以便您可以对其进行检查
  3. 任何不直接涉及您正在测试的预期行为的东西

同样,依赖关系是您作为类的使用者提供的东西,因此您希望使用它.否则,首先就没有这种依赖性.

Again, a dependency is something that you as the consumer of the class are providing, so you expect it to be used. Otherwise there is no point in having that dependency in the first place.

这篇关于BDD/TDD:依赖关系可以成为一种行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆