问题描述
我无法以声明方式表达以下代码:
I am having trouble expressing the following code in a declarative fashion:
[Theory]
[InlineData(@"-o=C:\Temp\someFile -p=1")]
[InlineData(@"-p=1 -o=C:\Temp\someFile")]
public void ParseMissingParameterShouldReturnCorrectResult(
string argsString
)
{
.....
var fixture = new Fixture();
fixture.Register<IFoo>(fixture.Create<Foo>);
fixture.Register<IBar>(fixture.Create<Bar>);
var sut = fixture.Create<SomeClass>();
.....
}
在我的生产代码中,我有类似的东西:
In my production code, I've got something like:
new SomeClass(new Foo(new Bar))
SomeClass 的构造函数定义为:
with the constructor of SomeClass being defined as:
public SomeClass(IFoo foo)
TIA,
大卫
SomeClass 看起来像
SomeClass looks like
public class SomeClass : IQux
{
private readonly IFoo _foo;
public SomeClass(IFoo foo)
{
_foo= foo;
}
推荐答案
您可以声明 SUT (这是 SomeClass
类型)作为测试方法的参数:
You can declare the SUT (which is the SomeClass
type) as a parameter on the test method:
[Theory]
[InlineAutoMockData(@"-o=C:\Temp\someFile -p=1")]
[InlineAutoMockData(@"-p=1 -o=C:\Temp\someFile")]
public void ParseMissingParameterShouldReturnCorrectResult(
string argsString,
SomeClass sut)
{
}
创建 [InlineAutoMockData]
属性的一种简单方法是:
An easy way to create the [InlineAutoMockData]
attribute is:
internal class InlineAutoMockDataAttribute : CompositeDataAttribute
{
internal InlineAutoMockDataAttribute (params object[] values)
: base(
new InlineDataAttribute(values),
new AutoDataAttribute(
new Fixture().Customize(
new CompositeCustomization(
new AutoMoqCustomization()))))
{
}
}
注意:
如果您还需要对 IFoo
或 IBar
模拟实例设置期望值,您可以冻结它们以便相同的 Frozen
实例在 SomeClass
实例中传递:
If you also need to setup expectations on the IFoo
or IBar
mocked instances you can freeze them so that the same Frozen
instances are passed in the SomeClass
instance:
[Theory]
[InlineAutoMockData(@"-o=C:\Temp\someFile -p=1")]
[InlineAutoMockData(@"-p=1 -o=C:\Temp\someFile")]
public void ParseMissingParameterShouldReturnCorrectResult2(
string argsString,
[Frozen]Mock<IFoo> mock,
[Frozen]Mock<IBar> stub,
SomeClass sut)
{
}
这篇关于Autofixture:如何声明性地表达以下代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!