【问题标题】:Test a controller using Autofixture that takes IOptions<T> as constructor parameter使用以 IOptions<T> 作为构造函数参数的 Autofixture 测试控制器
【发布时间】:2018-09-24 07:40:22
【问题描述】:

控制器类:

private readonly DbSettings _docDbSettings;

public CoursesController(IOptions<DbSettings> docDbSettings)
{
    if (docDbSettings == null) throw new ArgumentNullException(nameof(docDbSettings));
    _docDbSettings = docDbSettings.Value;
}

控制器测试类:

public class CoursesControllerTests
{
    private readonly IFixture _fixture;
    private readonly CoursesController _coursesController;
    private readonly DbSettings _docDbSettings;

    public CoursesControllerTests()
    {
        _fixture = new Fixture().Customize(new AutoFakeItEasyCustomization());

        // Need help here.
        _docDbSettings = _fixture.Create<IOptions<DbSettings>>();       
    }
}

错误:

Cannot implicitly convert type 'Microsoft.Extensions.Options.IOptions<Infrastructure.DbSettings>' to 'Infrastructure.DbSettings'

任何线索!

提前致谢。

【问题讨论】:

    标签: c# unit-testing autofixture


    【解决方案1】:

    您似乎正试图将_fixture.Create&lt;IOptions&lt;DbSettings&gt;&gt;() 返回的IOptions&lt;DbSettings&gt; 类型的对象分配给DbSettings 类型的变量,而这些类型不兼容

    您可以将 _docDbSettings 的类型更改为 IOptions&lt;DbSettings&gt; 或使用 AutoFixture 创建一个 DbSettings 对象,方法是:

    _docDbSettings = _fixture.Create<DbSettings>();
    

    顺便说一句,很高兴知道 AutoFixture 可以作为 auto-mocking container 工作,这意味着您可以要求它创建您的 CourseController 的实例,并且 AutoFixture 将确保为所有构造函数依赖项提供参数,在这种情况下IOptions&lt;DbSettings&gt;

    var systemUnderTest = _fixture.Create<CourseController>();
    

    您可以在 Mark Seemann 的 this article 中阅读有关如何将此模式与 AutoFixture 一起使用的更多信息。

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2012-05-14
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多