本文介绍了在执行单元测试时,asp.net核心中的TryValidateModel引发Null Reference Exception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写用于Asp.Net Core Web API的ModelState验证的单元测试.

I'm trying to write unit tests for ModelState validation for an Asp.Net Core Web API.

我读到,最好的方法是使用TryValidateModel函数.但是,每次我运行单元测试时,它都会引发NullReference异常.
我发现了很多建议controller.ModelState.AddModelError("","")的文章,但是我对此并不感兴趣,因为我认为它超出了实际模型验证的实际目的.

I read that, the best way to do so is to use TryValidateModel function. But, every time I run the unit test, it throws NullReference exception.
I found many articles suggesting controller.ModelState.AddModelError("",""), but I'm not interested in this, as I believe that it beats the actual purpose of the real model validation.

[TestMethod]
public void TestMethod1()
{
    var controller = new TestController();

    controller.Post(new Model());
}


public class TestController : Controller
{
    public IActionResult Post(Model model)
    {
        bool b = TryValidateModel(model)

        return Ok();
    }
}

TryValidateModel(model)总是从TryValidateModel(model, prefix)函数抛出NullReference异常.

TryValidateModel(model) always throws NullReference Exception from TryValidateModel(model, prefix) function.

感谢任何帮助.

推荐答案

这是配置/集成问题.

您可以在ASP.NET Core存储库中的问题中看到一些其他信息,并在github上的另一个.但是我可以告诉您最简单的修复方法(我使用过一次)

You can see some additional info in the issue in ASP.NET Core repo and another one on github.But I can tell you the easiest fix (I used it once)

        var objectValidator = new Mock<IObjectModelValidator>();
        objectValidator.Setup(o => o.Validate(It.IsAny<ActionContext>(), 
                                          It.IsAny<ValidationStateDictionary>(), 
                                          It.IsAny<string>(), 
                                          It.IsAny<Object>()));
        controller.ObjectValidator = objectValidator.Object;

这篇关于在执行单元测试时,asp.net核心中的TryValidateModel引发Null Reference Exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:38