[英]How to access field result from returned controller in MVC .net core
Whilst my controller functions correctly, I am getting a syntax error in my unit test on the "Assert" line for .Name
虽然我的控制器功能正常,但我在单元测试中的“Assert”行中出现语法错误.Name
IAction result does not contain a definition for "Name"... IAction 结果不包含“名称”的定义...
If I hover over "result" in debug mode I can see the data is in the result variable (Result > Model > Name).如果我在调试模式下将鼠标悬停在“结果”上,我可以看到数据在结果变量中(结果 > 模型 > 名称)。 I've tried accessing it with Result.Model.Name but that's a syntax error also.我试过用 Result.Model.Name 访问它,但这也是一个语法错误。
Unit test:单元测试:
[Fact]
public async Task TestGetNameById()
{
string expectedName = "Component";
using (var context = GetContextWithData())
using (var controller = new AssetTypesController(context))
{
var result = await controller.Details(2);
Assert.Equal(expectedName, result.Name);
}
}
Controller action:控制器动作:
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var assetType = await _context.AssetType
.SingleOrDefaultAsync(m => m.AssetTypeId == id);
if (assetType == null)
{
return NotFound();
}
return View(assetType);
}
Model模型
public class AssetType
{
[DatabaseGenerated(databaseGeneratedOption: DatabaseGeneratedOption.Identity)]
[Key]
public int AssetTypeId { get; set; }
[Required]
public string Name { get; set; }
}
That's because IActionResult
is not a type of AssetType
.这是因为IActionResult
不是一个类型的AssetType
。
Try something like this:尝试这样的事情:
[Fact]
public async Task TestGetNameById()
{
string expectedName = "Component";
using (var context = GetContextWithData())
{
var controller = new AssetTypesController(context);
var result = await controller.Details(2) as ViewResult;
var assetType = (AssetType) result.ViewData.Model;
Assert.Equal(expectedName, assetType.Name);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.