考虑以下测试,
[Theory, MyConventions]
public void GetClientExtensionReturnsCorrectValue(BuilderStrategy sut)
{
var expected = ""; // <--??? the value injected into BuilderStrategy
var actual = sut.GetClientExtension();
Assert.Equal(expected, actual);
}
以及我正在使用的自定义属性:
public class MyConventionsAttribute : AutoDataAttribute {
public MyConventionsAttribute()
: base(new Fixture().Customize(new AutoMoqCustomization())) {}
}
和SUT:
class BuilderStrategy {
private readonly string _clientID;
private readonly IDependency _dependency;
public void BuilderStrategy(string clientID, IDependency dependency) {
_clientID = clientID;
_dependency = dependency;
}
public string GetClientExtension() {
return _clientID.Substring(_clientID.LastIndexOf("-") + 1);
}
}
我需要知道在构造函数参数clientID
中注入了什么值,以便我可以使用它来与GetClientExtension
的输出进行比较。是否可以在将SUT注入测试方法时仍然编写这种测试方式?
答案 0 :(得分:5)
如果您将注入的clientID
(以及dependency
)公开为只读属性,则始终可以查询其值:
public class BuilderStrategy {
private readonly string _clientID;
private readonly IDependency _dependency;
public void BuilderStrategy(string clientID, IDependency dependency) {
_clientID = clientID;
_dependency = dependency;
}
public string GetClientExtension() {
return _clientID.Substring(_clientID.LastIndexOf("-") + 1);
}
public string ClientID
{
get { return _clientID; }
}
public IDependency Dependency
{
get { return _dependency; }
}
}
这doesn't break encapsulation, but is rather known as Structural Inspection。
通过此更改,您现在可以像这样重写测试:
[Theory, MyConventions]
public void GetClientExtensionReturnsCorrectValue(BuilderStrategy sut)
{
var expected = sut.ClientID.Substring(sut.ClientID.LastIndexOf("-") + 1);
var actual = sut.GetClientExtension();
Assert.Equal(expected, actual);
}
有些人不喜欢在单元测试中复制生产代码,但我宁愿争辩说,如果你遵循测试驱动开发,那就是复制测试代码的生产代码。
无论如何,这是一种称为Derived Value的技术。在我看来,as long as it retains a cyclomatic complexity of 1, we can still trust the test。此外,只要重复的代码只出现在两个地方,rule of three就表明我们应该保持这样。