gpt4 book ai didi

unit-testing - 自分流测试模式是否违反单一职责原则?

转载 作者:行者123 更新时间:2023-12-04 17:28:17 24 4
gpt4 key购买 nike

这些年来,我已经使用过几次自分流单元测试模式。正如我最近向某人解释的那样,他们认为这违反了 SRP。论点是测试类现在可以出于以下两个原因之一进行更改:当测试更改时,或者当测试正在实现的接口(interface)上的方法签名发生更改时。想了想,似乎这是一个正确的评估,但我想得到其他人的意见。想法?

引用:
http://www.objectmentor.com/resources/articles/SelfShunPtrn.pdf

最佳答案

我对此的看法是,测试类在技术上违反了 SRP,但并不违反 SRP 的精神。自分流的替代方法是让模拟类与测试类分开。
使用单独的模拟类,您可能会认为它是自包含的并满足 SRP,但是与模拟类属性的语义耦合仍然存在。所以,真的,我们没有实现任何有意义的分离。
以 PDF 中的示例为例:

public class ScannerTest extends TestCase implements Display
{
public ScannerTest (String name) {
super (name);
}
public void testScan () {
// pass self as a display
Scanner scanner = new Scanner (this);
// scan calls displayItem on its display
scanner.scan ();
assertEquals (new Item (“Cornflakes”), lastItem);
}
// impl. of Display.displayItem ()
void displayItem (Item item) {
lastItem = item;
}
private Item lastItem;
}
现在我们制作一个 Mock:
public class DisplayMock implements Display
{
// impl. of Display.displayItem ()
void displayItem (Item item) {
lastItem = item;
}

public Item getItem() {
return lastItem;
}
private Item lastItem;
}

public class ScannerTest extends TestCase
{
public ScannerTest (String name) {
super (name);
}
public void testScan () {
// pass self as a display
DisplayMock dispMock = new DisplayMock();
Scanner scanner = new Scanner (dispMock );
// scan calls displayItem on its display
scanner.scan ();
assertEquals (new Item (“Cornflakes”), dispMock.GetItem());
}
}
实际上(恕我直言) TestClass 的更高耦合度至 DisplayMock比违反 TestClass 的 SRP 更邪恶.此外,随着使用模拟框架,这个问题完全消失了。
编辑 我刚刚在 Robert C. Martin 的优秀著作 Agile Principles, Patterns, and Practices in C# 中遇到了对自分流模式的简短提及.以下是书中摘录:

We can accomplish this by using an abstract interface for the database. One implementation of this abstract interface uses the real database. Another implementation is test code written to simulate the behavior of the database and to check that the database calls are being made correctly. Figure 29-5 shows the structure. The PayrollTest module tests the PayrollModule by making calls to it and also implements the Database interface so that it can trap the calls that Payroll makes to the database. This allows PayrollTest to ensure that Payroll is behaving properly. It also allows PayrollTest to simulate many kinds of database failures and problems that are otherwise difficult to create. This is a testing pattern known as SELF-SHUNT, also sometimes known as mocking or spoofing.

Figure 29-5. PayrollTest SELF-SHUNTs database


因此,创造 SRP(在同一本书中详细讨论)的人对使用自分流模式毫无疑虑。鉴于此,我想说在使用这种模式时,您可以远离 OOP(面向对象的警察)。

关于unit-testing - 自分流测试模式是否违反单一职责原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com