我想对MVC控制器的最终ViewResult进行单元测试。
控制器代码作为应用程序运行时似乎可以正常工作。但是,当调试下面的单元测试方法时,它将开始逐步浏览控制器代码,并且当到达控制器中的这一行时,它似乎返回了单元测试。
HttpResponseMessage result = await getslots.GetDataFromIDMSapi(ssapiuri);
此行下的其余控制器代码未执行。因此,ViewResult不会返回到单元测试。
正在使用的测试框架是Microsoft.VisualStudio.TestTools.UnitTesting。
控制器方法
public async Task<ActionResult> Details(string positionNbr)
{
if (string.IsNullOrWhiteSpace(positionNbr))
{
throw new HttpException(400, "BadRequest");
}
string ssapiuri = getslots.BuildAPIuri($"/current/?positionNbr={positionNbr}");
HttpResponseMessage result = await getslots.GetDataFromIDMSapi(ssapiuri);
//right after executing the above, control is returned to the test method
if (result.StatusCode != HttpStatusCode.OK)
{
throw new HttpException(404, "NotFound");
}
XDocument doc = XDocument.Load(result.Content.ReadAsStreamAsync().Result);
IDMSElements elements = getslots.CopyDocToElements(doc);
PositionSlots myslots = (PositionSlots)elements;
myslots.UpdateDetails(db);
var model = new PositionSlot_vm();
model.PositionSlot = myslots.Positions.FirstOrDefault();
return View("Details", model);
}
称为异步方法
public async Task<HttpResponseMessage> GetDataFromIDMSapi(string ssapiuri)
{
HttpResponseMessage result = await MvcApplication.httpClientInstance.GetAsync(ssapiuri);
return result;
}
测试方法
public async Task Details_Given_Valid_Id_Can_Get_Position_Details()
{
//Arrange - create the controller
PositionController target = new PositionController();
//Act
//the next line starts going through the controller code
var viewResult = await target.Details(idToTest) as ViewResult;
PositionSlot_vm ps = viewResult.ViewData.Model as PositionSlot_vm;
//Assert
Assert.IsInstanceOfType(viewResult.ViewData.Model,typeof(PositionSlot_vm));
Assert.AreEqual(456, ps.PositionSlot.CostCenter);
Assert.AreEqual(123, ps.PositionSlot.EmployeeId);
Assert.AreEqual("xxx", ps.Department.DepartmentName);
}