问题描述
此测试是否正确使用了AutoFixture和Moq?是否写得尽可能简洁?如预期的那样,测试失败,并在编写正确的实现后通过.
Does this test make proper use of AutoFixture and Moq? Is it written as concisely as possible? The test fails, as expected, and passes after writing the correct implementation.
[Fact]
public void CustomerPropertyIsCorrect()
{
var fixture = new AutoMoqFixture();
var expected = fixture.Create<CardHolderCustomer>();
var builderMock = fixture
.Freeze<Mock<ICustomerAdapter>>()
.Setup(x => x.BuildCustomer()).Returns(expected);
var sut = fixture.Create<CardHolderViewModel>();
var actual = sut.Customer;
Assert.Equal(expected, actual);
}
推荐答案
看起来不错!但是,您也可以声明性地使用 使用xUnit.net 扩展名.
It's looking good! However, you can also use it declaratively with the xUnit.net extension.
假设测试中使用的类型定义为:
Assuming that the types used in the test are defined as:
public class CardHolderCustomer
{
}
public interface ICustomerAdapter
{
CardHolderCustomer BuildCustomer();
}
public class CardHolderViewModel
{
private readonly ICustomerAdapter adapter;
public CardHolderViewModel(ICustomerAdapter adapter)
{
if (adapter == null)
throw new ArgumentNullException("adapter");
this.adapter = adapter;
}
public CardHolderCustomer Customer
{
get
{
return this.adapter.BuildCustomer();
}
}
}
原始测试可以写为:
[Theory, DomainTestConventions]
public void CustomerPropertyIsCorrect2(
CardHolderCustomer expected,
[Frozen]Mock<ICustomerAdapter> builderStub,
CardHolderViewModel sut)
{
builderStub
.Setup(x => x.BuildCustomer())
.Returns(expected);
var actual = sut.Customer;
Assert.Equal(expected, actual);
}
DomainTestConventionsAttribute
定义为:
internal class DomainTestConventionsAttribute : AutoDataAttribute
{
internal DomainTestConventionsAttribute()
:base(new Fixture().Customize(new DomainTestConventions()))
{
}
}
DomainTestConventions
定义为:
internal class DomainTestConventions : CompositeCustomization
{
internal DomainTestConventions()
:base(new AutoMoqCustomization())
{
}
}
请注意,DomainTestConventions
是从CompositeCustomization
派生的,这基本上意味着您可以创建更多自定义项并将其作为参数添加到基本构造函数中.
Note that DomainTestConventions
derives from CompositeCustomization
which basically means that you can create more Customizations and add them as parameters to the base constructor.
您还可以阅读:
- The order of AutoFixture Customizations matter
- AutoData Theories with AutoFixture
- Keep your unit tests DRY with AutoFixture Customizations
- AutoFixture, xUnit.net, and Auto Mocking
希望有帮助.
这篇关于此测试是否正确使用了AutoFixture和Moq?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!