【问题标题】:How to access field result from returned controller in MVC .net core如何从 MVC .net 核心中返回的控制器访问字段结果
【发布时间】:2018-03-10 07:09:33
【问题描述】:

虽然我的控制器功能正常,但我的 单元测试.Name 的“断言”行中遇到语法错误

IAction 结果不包含“名称”的定义...

如果我在调试模式下将鼠标悬停在“结果”上,我可以看到数据在结果变量中(结果 > 模型 > 名称)。我尝试使用 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; }
}

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core async-await xunit


    【解决方案1】:

    这是因为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);
        }
    }
    

    【讨论】:

    • 太好了,谢谢。我不太明白为什么我不能做AssetType assetType = result.ViewData.Model - 你知道为什么 ReSharper 会警告我在 result.ViewData.Model 中的“结果”说“可能的 System.NullReferenceException”吗?
    • @egmfrs 可能是因为 controller.Details(2) 可以返回为 null。
    • 更改为 (ViewResult)await controller.Details(2);修复了语法警告,但随后单元测试失败。我会保持原样。
    • 添加 Assert.NotNull(result);在 var 结果行之后直接修复语法警告。
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2017-07-29
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多