虽然我的控制器功能正常,但我在单元测试上的" Assert" .Name
执行结果不包含"名称" ...
的定义
如果我将鼠标悬停在"结果"在调试模式下,我可以看到数据在结果变量中(结果>模型>名称)。我尝试使用Result.Model.Name访问它,但这也是一个语法错误。
单元测试:
[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);
}
}
控制器操作:
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);
}
模型
public class AssetType
{
[DatabaseGenerated(databaseGeneratedOption: DatabaseGeneratedOption.Identity)]
[Key]
public int AssetTypeId { get; set; }
[Required]
public string Name { get; set; }
}
答案 0 :(得分:2)
那是因为IActionResult
不是AssetType
的类型。
尝试这样的事情:
[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);
}
}