无法使用最小起订量模拟 Configuration.Formatters

Unable to mock Configuration.Formatters using Moq

我正在开发 ASP.NET 网络 API 应用程序。我正在对应用程序中的每个组件进行单元测试。我正在使用 Moq 单元测试框架来模拟数据。现在我想在我的单元测试中模拟 Configuration.Formatters.JsonFormatter 因为我在单元测试下的操作如下使用它:

public HttpResponseMessage Register(model)
{
    return new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadRequest,
                Content = new ObjectContent<List<string>>(errors, Configuration.Formatters.JsonFormatter)
            };
}

我正在尝试在单元测试中模拟 Configuration.Formatters.JsonFormatter,如下所示。

[TestMethod]
public void Register_ReturnErrorsWithBadRequest_IfValidationFails()
{
    PostUserRegistration model = new PostUserRegistration {
        Name = "Wai Yan Hein",
        Email = "waiyanhein@gmail.com",
        Password = ""
    };

    Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>();
    Mock<MediaTypeFormatterCollection> formatterCollection = new Mock<MediaTypeFormatterCollection>();
    formatterCollection.Setup(x => x.JsonFormatter).Returns(formatterMock.Object);
    Mock<HttpConfiguration> httpConfigMock = new Mock<HttpConfiguration>();
    httpConfigMock.Setup(x => x.Formatters).Returns(formatterCollection.Object);
    Mock<IAccountRepo> accRepoMock = new Mock<IAccountRepo>();

    AccountsController controller = new AccountsController(accRepoMock.Object);

    controller.Configuration = httpConfigMock.Object;
    controller.ModelState.AddModelError("", "Faking some model error");
    HttpResponseMessage response = controller.Register(model);
    Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.BadRequest);
}

当我 运行 我的单元测试时,它给我这个错误。

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: x => x.JsonFormatter

那么,我该如何修复该错误以及如何模拟 Configuration.Formatters.JsonFormatter

您不必测试框架是否正在执行其设计目的。相反,类似于之前在评论中提出的建议,我建议使用 ApiController 的内置方法,并将操作重构为该版本 Asp.Net Web [=22= 文档中建议的语法]

public IHttpActionResult Register(PostUserRegistration model) {
    if (!ModelState.IsValid)
        return BadRequest(ModelState); //<-- will extract errors from model state

    //...code removed for brevity

    return Ok();
}

上述方法的单元测试的简单示例可能如下所示...

[TestMethod]
public void Register_ReturnErrorsWithBadRequest_IfValidationFails() {            
    //Arrange
    PostUserRegistration model = new PostUserRegistration {
        Name = "Wai Yan Hein",
        Email = "waiyanhein@gmail.com",
        Password = ""
    };

    var accRepoMock = new Mock<IAccountRepo>();
    var controller = new AccountsController(accRepoMock.Object);
    controller.ModelState.AddModelError("", "Faking some model error");

    //Act
    var response = controller.Register(model) as InvalidModelStateResult; //<-- Note the cast here

    //Assert
    Assert.IsNotNull(response);
}

如果注入的依赖项不会在被测方法中 referenced/invoked,您也可以放弃模拟并注入 null。然而,这取决于原始问题中未提供的代码。