我试图对我的控制器进行单元测试,该控制器包含对ModelState.IsValid的检查,但由于某种原因,无论我做什么,我总是在尝试访问ModelState时都会出现null异常(在单元测试和控制器功能)。
每个地方我检查人们只是使用ModelState.Clear()/。AddModelError(),它似乎适用于他们。有些人说当mvc版本不同时他们会得到一个例外但是我已经检查了它们并且它们是相同的。
我能错过什么?
继承单元测试代码:
private Mock<IRegistrationService> registrationService;
private RegistrationController registrationCtrl;
public RegisteringANewUser()
{
registrationService = new Mock<IRegistrationService>();
registrationCtrl = new RegistrationController(registrationService.Object);
registrationCtrl.ModelState.Clear(); <- throws exception
}
[Fact]
public void ShouldRegisterUser_WhenInputIsCorrect()
{
var registration = RegistrationHelper.CreateRegistrationVM("username", "password", "asfa@asf.com");
registrationCtrl.Post(registration);
registrationService.Verify(s => s.Register(registration), Times.Once);
}
[Fact]
public void ShouldReturnBadRequest_WhenInputIsInvalid()
{
var registration = RegistrationHelper.CreateRegistrationVM("", "", "");
registrationCtrl.ModelState.AddModelError("Error", "Error"); <- throws exception
var result = registrationCtrl.Post(registration);
Assert.Equal((int)HttpStatusCode.BadRequest, result.StatusCode);
}
正在测试的控制器功能:
public HttpStatusCodeResult Post(RegistrationVM registration)
{
if (!ModelState.IsValid) <- throws exception
{
return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
}
_registrationService.Register(registration);
return new HttpStatusCodeResult((int)HttpStatusCode.OK);
}
单元测试库的project.json:
{
"version": "1.0.0-*",
"dependencies": {
"Web": "1.0.0-*",
"Moq": "4.2.1409.1722",
"Xunit.KRunner": "1.0.0-rc1-10618",
"Microsoft.AspNet.Mvc": "6.0.0-beta1"
},
"frameworks": {
"aspnet50": {
"dependencies": {
}
}
},
"commands": {
"test": "Xunit.KRunner"
}
}
对于网站项目:
{
/* Click to learn more about project.json http://go.microsoft.com/fwlink/?LinkID=517074 */
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-beta1",
//"Microsoft.AspNet.Mvc.WebApiCompatShim": "6.0.0-beta1",
"Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
"Microsoft.AspNet.Security.Cookies": "1.0.0-beta1",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta1",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta1",
"Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta1",
"Microsoft.Framework.Logging": "1.0.0-beta1",
"Microsoft.Framework.Logging.Console": "1.0.0-beta1",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta1",
"mongocsharpdriver": "1.10.0.0-rc1"
},
"commands": {
/* Change the port number when you are self hosting this application */
"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000",
"gen": "Microsoft.Framework.CodeGeneration"
},
"frameworks": {
"aspnet50": { },
"aspnetcore50": { } <- tried to remove this as I dont have it in my unit test lib without success
},
"exclude": [
"wwwroot",
"node_modules",
"bower_components"
],
"packExclude": [
"node_modules",
"bower_components",
"**.kproj",
"**.user",
"**.vspscc"
],
"scripts": {
"postrestore": [ "npm install" ],
"prepare": [ "grunt bower:install" ]
}
}
答案 0 :(得分:1)
这确实是一个差距(直到beta3)。由Issue
跟踪在Beta3版本中(或者您可以在一天左右的时间内完成开发版本),我们将初始化一个仅测试ViewDataDictionary
的单元,以便您的单元测试将变为空{{1} }。
以下是ModelState
Controller.cs
并且(代码没有变化)
[Activate]
public ViewDataDictionary ViewData
{
get
{
if (_viewData == null)
{
// This should run only for the controller unit test scenarios
_viewData =
new ViewDataDictionary(new EmptyModelMetadataProvider(),
ActionContext?.ModelState ?? new ModelStateDictionary());
}
return _viewData;
}
set
{
if (value == null)
{
throw
new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(ViewData));
}
_viewData = value;
}
}