在AspNetCore上进行单元测试控制器模型验证 [英] Unit test controller model validation on AspNetCore

查看:159
本文介绍了在AspNetCore上进行单元测试控制器模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASPNET Core项目中,我试图创建一些单元测试以验证我的数据验证逻辑是否正常工作.

In an ASPNET Core project I am trying to create some unit tests that would verify my data validation logic works fine.

我的控制器非常简单:

[HttpPost]
[Route("Track")]
public void Track([FromBody] DataItem item)
{
    if (!ModelState.IsValid) throw new ArgumentException("Bad request");

    _dataItemSaver.SaveData(item);
}

我正在使用一个测试基类,该基类会将_myController对象设置为被测试的控制器.

I am using a test base class that would set up the _myController object as the controller under test.

    public ControllerTestBase()
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"buildversion.json", optional: true)
            .AddEnvironmentVariables();
        _config = builder.Build();

        var services = new ServiceCollection()
            .AddEntityFrameworkInMemoryDatabase()
            .AddDbContext<MyDbContext>(options =>
            {
                options.UseInMemoryDatabase();
            })
            .AddScoped<IDataItemSaver, DataItemSQLStorageService>()
            .AddScoped<MyController>()
            .Configure<MyConfig>(_config.GetSection(nameof(MyConfig)));

        services
            .AddMvc(mvcOptions =>
                {
                    mvcOptions.Filters.AddService(typeof(GlobalExceptionFilter), 0);
                });

        _additionalDISetupActions?.Invoke(services);

        _serviceProvider = services.BuildServiceProvider();

        _myController = _serviceProvider.GetService<MyController>();
    }

再次测试非常简单:

    [TestMethod]
    public void Prop3Required()
    {
        // Arrange
        var dataItem = new DataItem()
        {
            Prop1 = "Prop1",
            Prop2 = "Prop2"
        };

        // Act & Assert
        Assert.ThrowsException<ArgumentException>(() => _myController.Track(dataItem));
    }

运行单元测试时,即使我的DataItem缺少必需的属性(在本示例中为Prop3),我仍发现ModelState.IsValidtrue.当通过具有相同输入的Web测试控制器时,验证工作正常(将ModelState.IsValid返回false).

I am finding though that ModelState.IsValid is true when running a unittest even when my DataItem is missing required attributes (Prop3 in this example). When testing the controller through the web with the same input, the validation works correctly (returning false for ModelState.IsValid).

如何从单元测试中正确触发ASPNET Core逻辑以进行模型状态验证?

How do I properly trigger the ASPNET Core logic for modelstate validation from a unit test?

推荐答案

您应该查看与ASP.NET Core的集成测试(

You should take a look at Integration Testing with ASP.NET Core (https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testing), it is a very simple way to host your application in a test context and test your entire pipeline.
As explained in the documentation you could do something like this in your test method:

_server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
_client = _server.CreateClient();
// Pass a not valid model 
var response = await _client.PostAsJsonAsync("Track", new DataItem());
Assert.IsFalse(response.IsSuccessStatusCode);

这篇关于在AspNetCore上进行单元测试控制器模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆