在.NET的核心,我们有在呼唤具有依赖注入ViewComponent,按照微软的文档模式的控制器操作在这里。
如果我们有一个控制器动作返回这样的渲染视图:
public class MyController : Controller
{
private readonly IToDoContext _todoContext;
public MyController(IToDoContext todoContext)
{
_todoContext = todoContext;
}
public IActionResult IndexVC()
{
return ViewComponent("PriorityList", new { maxPriority = 3, isDone = false });
}
}
还有一个具有如下依赖注入的 ViewComponent:
public class PriorityListViewComponent : ViewComponent
{
private readonly ToDoContext db;
public PriorityListViewComponent(ToDoContext context)
{
db = context;
}
public async Task<IViewComponentResult> InvokeAsync(int maxPriority, bool isDone)
{
var items = await GetItemsAsync(maxPriority, isDone);
return View(items);
}
private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
{
return db.ToDo.Where(x => x.IsDone == isDone && x.Priority <= maxPriority).ToListAsync();
}
}
我们如何在控制器动作单元测试中将 ToDoContext 注入到 ViewComponent 中?到目前为止, result.Model 始终为空,因为似乎没有办法将 ToDoContext db 注入控制器,然后再注入 ViewComponent。
[Fact]
public void Should_return_viewcomponent()
{
var mockToDoContext = new Mock<IToDoContext>();
mockToDoContext.Setup(m => m.Get()).ReturnsAsync(new ToDoContext());
var sut = new MyController(mockToDoContext.Object);
var result = sut.PriorityListViewComponent("myparams") as ViewComponentResult;
// ToDoContext db is never set, so the result.Model is always null
}
隔江千里
相关分类