.NET CORE MVC ViewComponent xUnit 测试

.NET CORE MVC ViewComponent xUnit Testing

我已经开始将 xUnit 用于示例 .NET CORE MVC 项目,我正在努力向 ViewComponent 添加测试,其中包括 IOptionsIHostingEnvironment。这是一个简单的视图组件,returns 值来自 appsettings.json 文件,它本身可以正常工作。

appsettings.json 片段:

"Application": {"Name": "My App","Version": "1.0.0","Author": "John Doe", "Description": "Just a template!"}

视图组件:

[ViewComponent(Name = "Footer")]
public class FooterViewComponent : ViewComponent
{
    private readonly IOptions<AppSettings.Application> _app;
    private readonly IHostingEnvironment _env;

    public FooterViewComponent(IOptions<AppSettings.Application> app, IHostingEnvironment env)
    {
        _app = app;
        _env = env;
    }

    public IViewComponentResult Invoke()
    {
        var vm = new FooterViewModel();
        {
            vm.AppName = _app.Value.Name;
            vm.AppVersion = _app.Value.Version;
            vm.AppEnvironment = _env.EnvironmentName;
        }

        return View(vm);
    }
}

我想测试 return 类型是 ViewComponent 结果并且视图模型不为空。

ViewComponent 测试:

public class FooterViewComponentTest
{
    public class Should
    {
        [Fact]
        public void ReturnViewCompnentWithViewModel()
        {
            // Arrange
            var viewComp = new FooterViewComponent(??????????);

            // Act
            var result = viewComp ??????????;

            // Assert
            Assert.IsType<ViewComponentResult>(result);

        }
    }
}

我仍在努力解决这个问题,并将根据我的发现编辑我的片段。有人有什么建议吗?我应该用这种格式编写测试吗?

使用众所周知的 Moq 框架,您可以编写依赖抽象的模拟对象并将它们注入组件的构造函数中,如下所示:

public class FooterViewComponentTest
{
    public class Should
    {
        [Fact]
        public void ReturnViewCompnentWithViewModel()
        {
            // Arrange
            var appSettings = new AppSettings.Application();
            appSettings.AppName = "app";
            appSettings.Version = "1.0";
            var optionsMock = new Mock<IOptions<AppSettings.Application>>();
            optionsMock.Setup(o => o.Value).Returns(appSettings);

            var hostingMock = new Mock<IHostingEnvironment>();
            hostingMock.Setup(h => h.Environment).Returns("Test");

            var viewComp = new FooterViewComponent(optionsMock.Object, hostingMock.Object);

            // Act
            var result = viewComp.Invoke();

            // Assert
            Assert.IsType<ViewComponentResult>(result);

        }
    }
}

参考 Moq Quickstart 以更好地了解如何使用模拟框架。