且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Autofixture和的WebAPI控制器

更新时间:2023-02-12 16:56:26

这是绝对推荐的方式来写与AutoFixture测试。问题是pretty容易修复。

This is definitely the recommended way to write tests with AutoFixture. The issue is pretty easy to fix.

无需实现在博客文章中描述的[AutoMoqData]属性的,我建议你创建一个稍微不同的属性和定制 - 一组基本上将作为一个完整的单元测试项目一组约定。我总是这样做,我总是竭尽全力有只为一个单元测试项目单套约定。单套约定的帮助我保持我的测试(与 SUT S)是一致的。

Instead of implementing the [AutoMoqData] attribute as described in the blog post, I'd recommend creating a slightly different attribute and Customization - a set that basically will act as a set of conventions for an entire unit test project. I always do this, and I always go to great lengths to have only a single set of conventions for a single unit test project. A single set of conventions help me keep my tests (and the SUTs) consistent.

public class AutoMyWebApiDataAttribute : AutoDataAttribute
{
    public AutoMyWebApiDataAttribute()
        : base(new Fixture().Customize(new MyWebApiCustomization()))
    {
    }
}

该MyWebApiCustomization可以这样来定义:

The MyWebApiCustomization could be defined like this:

public class MyWebApiCustomization : CompositeCustomization
{
    public MyWebApiCustomization()
        : base(
            new HttpSchemeCustomization(),
            new AutoMoqCustomization(),
        )
    {
    }

    private class HttpSchemeCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Inject(new UriScheme("http"));
        }
    }
}

请注意额外HttpSchemeCustomization类 - 这应该做的伎俩

Note the additional HttpSchemeCustomization class - that should do the trick.

请注意,的自定义事项的顺序。