unit-testing - Autofixture 和 WebApi Controller

标签 unit-testing asp.net-web-api moq xunit autofixture

我正在使用 AutoFixture 尝试为 WebApi 站点测试我的 Controller 。如 Ploeh's blog 所述,我将 AutoData 功能与 Moq 一起使用.

我的 Controller 在构造函数中使用 IDepartmentManager。这是我的测试:

[Theory, AutoMoqData]
public void GetCallsManagerCorrectly(
    [Frozen]Mock<IDepartmentManager> departmentManagerMock,
    DepartmentsController sut)
{
    // Fixture setup
    // Exercise system
    sut.Get();
    // Verify outcome
    departmentManagerMock.Verify(d => d.GetAllDepartments(), Times.Exactly(1));
    // Teardown
}

当我运行此测试时,它失败并显示以下内容:

GetCallsManagerCorrectly has failed:
System.InvalidOperationException : An exception was thrown while getting data for theory Provision.Tests.WebApiControllerTests.DepartmentControllerTests.GetCallsManagerCorrectly: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Only 'http' and 'https' schemes are allowed. Parameter name: value at System.Net.Http.HttpRequestMessage.set_RequestUri(Uri value)



首先,这仍然是编写这些测试的有效且推荐的方法吗?我喜欢它让一切变得多么小。

其次,我应该怎么做才能解决这个问题?如果我将测试更改为:
[Theory, AutoMoqData]
public void GetCallsManagerCorrectly(
    [Frozen]Mock<IDepartmentManager> departmentManagerMock)
{
    // Fixture setup
    DepartmentsController sut =
        new DepartmentsController(departmentManagerMock.Object);
    // Exercise system
    sut.Get();
    // Verify outcome
    departmentManagerMock.Verify(d => d.GetAllDepartments(), Times.Exactly(1));
    // Teardown
}

它通过了,但是我失去了自动建立 Controller 的能力,如果我向构造函数添加参数仍然可以。

最佳答案

这绝对是使用 AutoFixture 编写测试的推荐方式。这个问题很容易解决。

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

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

MyWebApiCustomization 可以这样定义:
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 类 - 这应该可以解决问题。

请注意 the order of Customizations matters .

关于unit-testing - Autofixture 和 WebApi Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12605977/

相关文章:

dependency-injection - ASP.Net Web API DependencyResolver - 试图解决许多我不关心的内部依赖关系的框架?

php - 您将如何测试一个可以向查询添加数十个不同过滤器的类?

c# - 具有不同参数类型的web api多个post方法

c# - 自托管 WebAPI 和多种 post 和 get 方法

c# - 使用 Moq 测试 get/set

c# - 测试类 A 中的方法是否已从类中的另一个方法调用

unit-testing - 向我指出一些带有*(单元)测试的开源项目

JavaScript,随机数的 Mocha 测试

ios - 使用 PromiseKit 的单元测试功能

c# - 初学者在使用模拟框架 C# .net 时遇到问题