【问题标题】:.NET CORE MVC ViewComponent xUnit Testing [duplicate].NET CORE MVC ViewComponent xUnit 测试 [重复]
【发布时间】:2018-02-11 11:34:22
【问题描述】:

我已经开始将 xUnit 用于示例 .NET CORE MVC 项目,我正在努力将测试添加到 ViewComponent,其中包括 IOptionsIHostingEnvironment。它是一个简单的视图组件,它从 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);
    }
}

我想测试一下返回类型是ViewComponent结果并且View Model不为空。

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

        }
    }
}

我仍在努力,并将根据我的发现编辑我的 sn-ps。有人有什么建议吗?我应该以这种格式编写测试吗?

【问题讨论】:

  • 模拟依赖并将它们注入到被测对象中,通过调用被测方法并断言结果符合预期。

标签: c# unit-testing asp.net-core-mvc xunit asp.net-core-viewcomponent


【解决方案1】:

使用众所周知的 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 以更好地了解如何使用模拟框架。

【讨论】:

  • 谢谢各位。测试现在正在工作。将 Assert 操作更改为:Assert.IsType(result);
猜你喜欢
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2018-05-16
  • 2018-05-27
  • 2020-04-02
  • 1970-01-01
相关资源
最近更新 更多