我在xUnit测试中使用the excellent Shouldly
library,但发现自己在不同测试中使用了确定的断言序列,因此我将它们组合为新的断言扩展方法-但是当我这样做时,我会丢失[C0 ]的上下文声明消息。
这是我的旧代码,可与Shouldly
配合使用,以在Shouldly
断言错误中包括源代码级信息和呼叫站点上下文:
Shouldly
我将其转换为同一项目中的此新扩展方法:
Shouldly
因此我的测试更改为:
[Fact]
public void Dict_should_contain_valid_Foobar_Bar_entry()
{
IDictionary<String,Bar> dict = ...
dict.TryGetValue( "Foobar", out Bar bar ).ShouldBeTrue();
bar.ShouldNotBeNull();
bar.ChildList.Count.ShouldBe( expected: 3 );
bar.Message.ShouldBeNull();
}
[Fact]
public void Dict_should_contain_valid_Barbaz_Bar_entry()
{
IDictionary<String,Bar> dict = ...
dict.TryGetValue( "Barbaz", out Bar bar ).ShouldBeTrue();
bar.ShouldNotBeNull();
bar.ChildList.Count.ShouldBe( expected: 3 );
bar.Message.ShouldBeNull();
}
...但是现在我的“应有断言”消息不包含来自public static void ShouldBeValidBar( this IDictionary<String,Bar> dict, String barName )
{
dict.ShouldNotBeNull();
dict.TryGetValue( barName, out Bar bar ).ShouldBeTrue();
bar.ShouldNotBeNull();
bar.ChildList.Count.ShouldBe( expected: 3 );
bar.Message.ShouldBeNull();
}
的任何上下文信息,而仅包含来自[Fact]
public void Dict_should_contain_valid_Foobar_Bar_entry()
{
IDictionary<String,Bar> dict = ...
dict.ShouldBeValidBar( "Foobar" );
}
[Fact]
public void Dict_should_contain_valid_Barbaz_Bar_entry()
{
IDictionary<String,Bar> dict = ...
dict.ShouldBeValidBar( "Barbaz" );
}
的上下文。
如何指示Dict_should_contain_valid_Foobar_Bar_entry
忽略ShouldBeValidBar
的上下文并改为使用其父级呼叫站点?
Shouldly
-并且在读取ShouldBeValidBar
之后,我发现它确定了堆栈跟踪中的哪些条目可以忽略该方法(或该方法的包含类型)and reading articles about how Shouldly
works(Shouldly
)堆栈跟踪的每一帧:the source of Shouldly's secret-sauce: SourceCodeTextGetter
SourceCodeTextGetter
因此,只需将by the presence of the[ShouldlyMethods]
attribute属性添加到我的扩展方法或扩展方法类中即可:
[ShouldlyMethods]
现在,我的断言错误具有Shouldly.ShouldlyMethodsAttribute
调用位置的上下文。哇!