title: Unit test controller model validation on AspNetCore
body: <p>In an ASPNET Core project I am trying to create some unit tests that would verify my data validation logic works fine.</p>
  
  <p>My controller is very simple:</p>
  
  <pre><code>[HttpPost]
  [Route("Track")]
  public void Track([FromBody] DataItem item)
  {
      if (!ModelState.IsValid) throw new ArgumentException("Bad request");
  
      _dataItemSaver.SaveData(item);
  }
  </code></pre>
  
  <p>I am using a test base class that would set up the <code>_myController</code> object as the controller under test.</p>
  
  <pre><code>    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&lt;MyDbContext&gt;(options =&gt;
              {
                  options.UseInMemoryDatabase();
              })
              .AddScoped&lt;IDataItemSaver, DataItemSQLStorageService&gt;()
              .AddScoped&lt;MyController&gt;()
              .Configure&lt;MyConfig&gt;(_config.GetSection(nameof(MyConfig)));
  
          services
              .AddMvc(mvcOptions =&gt;
                  {
                      mvcOptions.Filters.AddService(typeof(GlobalExceptionFilter), 0);
                  });
  
          _additionalDISetupActions?.Invoke(services);
  
          _serviceProvider = services.BuildServiceProvider();
  
          _myController = _serviceProvider.GetService&lt;MyController&gt;();
      }
  </code></pre>
  
  <p>The test again is very simple:</p>
  
  <pre><code>    [TestMethod]
      public void Prop3Required()
      {
          // Arrange
          var dataItem = new DataItem()
          {
              Prop1 = "Prop1",
              Prop2 = "Prop2"
          };
  
          // Act &amp; Assert
          Assert.ThrowsException&lt;ArgumentException&gt;(() =&gt; _myController.Track(dataItem));
      }
  </code></pre>
  
  <p>I am finding though that <code>ModelState.IsValid</code> is <code>true</code> when running a unittest even when my <code>DataItem</code> is missing required attributes (<code>Prop3</code> in this example). When testing the controller through the web with the same input, the validation works correctly (returning <code>false</code> for <code>ModelState.IsValid</code>).</p>
  
  <p>How do I properly trigger the ASPNET Core logic for modelstate validation from a unit test?</p>