我正在为我们的控制器编写一些单元测试。我们有以下简单的控制器。
public class ClientController : Controller
{
[HttpPost]
public ActionResult Create(Client client, [DataSourceRequest] DataSourceRequest request)
{
if (ModelState.IsValid)
{
clientRepo.InsertClient(client);
}
return Json(new[] {client}.ToDataSourceResult(request, ModelState));
}
}
对此的单元测试如下:
[Test]
public void Create()
{
// Arrange
clientController.ModelState.Clear();
// Act
JsonResult json = clientController.Create(this.clientDto, this.dataSourceRequest) as JsonResult;
// Assert
Assert.IsNotNull(json);
}
控制器上下文是用以下代码伪造的:
public class FakeControllerContext : ControllerContext
{
HttpContextBase context = new FakeHttpContext();
public override HttpContextBase HttpContext
{
get
{
return context;
}
set
{
context = value;
}
}
}
public class FakeHttpContext : HttpContextBase
{
public HttpRequestBase request = new FakeHttpRequest();
public HttpResponseBase response = new FakeHttpResponse();
public override HttpRequestBase Request
{
get { return request; }
}
public override HttpResponseBase Response
{
get { return response; }
}
}
public class FakeHttpRequest : HttpRequestBase
{
}
public class FakeHttpResponse : HttpResponseBase
{
}
}
当Create
控制器操作尝试调用该ToDataSourceResult
方法时会发生异常。
System.EntryPointNotFoundException : Entry point was not found.
调试显示 ModelState 内部字典在单元测试中为空(而不是在标准上下文中运行时)。如果ModelState
从ToDataSourceResult
方法中删除,则测试成功通过。任何帮助深表感谢。