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

时间:2018-09-24 07:40:22

标签: c# unit-testing autofixture

控制器类:

private readonly DbSettings _docDbSettings;

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

Controller Tests类:

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'

任何线索!

谢谢。

1 个答案:

答案 0 :(得分:1)

似乎您试图将IOptions<DbSettings>返回的_fixture.Create<IOptions<DbSettings>>()类型的对象分配给类型DbSettings的变量,当这些类型不兼容

您可以将_docDbSettings的类型更改为IOptions<DbSettings>或使用自动修复功能创建一个DbSettings对象,方法是:

_docDbSettings = _fixture.Create<DbSettings>();

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

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

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