This question already has answers here:
How to unit test ViewComponent.Invoke()?
                                
                                    (2个答案)
                                
                        
                                去年关闭。
            
                    
我已经开始将xUnit用于一个示例.NET CORE MVC项目,并且正在努力将测试添加到包含ViewComponentIOptionsIHostingEnvironment中。这是一个简单的视图组件,可从appsettings.json文件返回值,并且它本身可以正常工作。

appsettings.json代码段:

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


ViewComponent:

[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结果,并且视图模型不为空。

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 Framework,您可以编写依赖关系抽象的模拟对象,并将其注入组件的构造函数中,如下所示:

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可以更好地了解如何使用模拟框架。

07-24 19:40