我是单元测试的新手。不确定要对什么进行测试,我继续并在 ClientController 上使用索引 View 开始了一个测试。我在为声明为异步任务的索引 View 编写测试方法时遇到问题。我想要做的是确保此操作返回数据。不确定这个测试有多重要,但我想学习在 MVC 5 中编写测试的方法。似乎在为异步 View 编写测试时遇到问题。
管理服务类
public IQueryable<Client> GetAllClients(bool includeDeleted = false)
{
var query = context.Clients.AsQueryable();
if (!includeDeleted) query = query.Where(c => !c.IsDeleted);
return query;
}
客户端 Controller
public ClientController(IApplicationContext appContext, IManagementService adminService, IDomainService domainService)
{
this.adminService = adminService;
this.appContext = appContext;
this.domainService = domainService;
}
public async Task<ActionResult> Index()
{
var clients = adminService.GetAllClients();
return View(await clients.ToListAsync());
}
//测试
[TestMethod]
public void Index()
{
//Arrange
var mgmtmockContext = new Mock<IManagementService>();
List<Client> db = new List<Client>();
db.Add(new Client { ClientId = 1, Name = "Test Client 1" });
db.Add(new Client { ClientId = 2, Name = "Test Client 2" });
mgmtmockContext
.Setup(m => m.GetAllClients(false))
.Returns(() => { return db.AsQueryable(); });
//Act
ClientController controller = new ClientController(null, mgmtmockContext.Object, null);
var result = controller.Index() as Task<ActionResult>;
//Assert
Assert.IsNotNull(result);
}
创建 Controller 的实例后,我不确定如何将模拟对象传递给 Index() 以便测试此 View 返回的数据。
我想要断言的是 Assert.AreEqual(2, result.Count()) 这样我就可以运行这个测试。
最佳答案
为了从结果中得到列表,你需要做两件事:
- 获取任务的实际结果
- 从 Action 结果中得到模型
这是你如何做到这一点:
var result = controller.Index() as Task<ViewResult>;
// Get the actual result from the task
var viewresult = result.Result;
// Get the model from the viewresult and cast it to the correct type
// (notice in the first line I changed ActionResult to ViewResult to make sure we can access the model.
var model = (List<Client>)(viewresult.Model);
//Assert
Assert.IsNotNull(result);
Assert.AreEqual(2, model.Count);
关于c# - MVC 5 异步任务<ActionResult> 索引 View 的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23352377/