【发布时间】:2018-02-11 11:34:22
【问题描述】:
我已经开始将 xUnit 用于示例 .NET CORE MVC 项目,我正在努力将测试添加到 ViewComponent,其中包括 IOptions 和 IHostingEnvironment。它是一个简单的视图组件,它从 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