简体   繁体   English

使用带 IOptions 的 Autofixture 测试控制器<T>作为构造函数参数

[英]Test a controller using Autofixture that takes IOptions<T> as constructor parameter

Controller class:控制器类:

private readonly DbSettings _docDbSettings;

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

Controller Tests class:控制器测试类:

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>>();       
    }
}

Error:错误:

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

Any clues!任何线索!

Thanks in advance.提前致谢。

It seems you're trying to assign an object of type IOptions<DbSettings> returned by _fixture.Create<IOptions<DbSettings>>() to a variable of type DbSettings when those types aren't compatible .看来你要指定类型的对象IOptions<DbSettings>由归国_fixture.Create<IOptions<DbSettings>>()以类型的变量DbSettings当这些类型是不兼容的

You can either change the type of _docDbSettings to IOptions<DbSettings> or create a DbSettings object with AutoFixture by saying:您可以将_docDbSettings的类型_docDbSettingsIOptions<DbSettings>或通过以下DbSettings使用 AutoFixture 创建DbSettings对象:

_docDbSettings = _fixture.Create<DbSettings>();

By the way, it's good to know that AutoFixture can work as an auto-mocking container , meaning that you can ask it to create an instance of your CourseController and AutoFixture will make sure to provide arguments for all of the constructor dependencies, in this case IOptions<DbSettings> :顺便说一句,很高兴知道 AutoFixture 可以用作自动模拟容器,这意味着您可以要求它创建CourseController的实例,并且 AutoFixture 将确保为所有构造函数依赖项提供参数,在这种情况下IOptions<DbSettings> :

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

You can read more about how to use this pattern with AutoFixture in this article by Mark Seemann.您可以在 Mark Seemann 的这篇文章中阅读有关如何将此模式与 AutoFixture 结合使用的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM