Asp.net mvc 4 使用剑道UI在MVC4中对控制器动作进行单元测试

Asp.net mvc 4 使用剑道UI在MVC4中对控制器动作进行单元测试,asp.net-mvc-4,kendo-ui,kendo-asp.net-mvc,Asp.net Mvc 4,Kendo Ui,Kendo Asp.net Mvc,我正在为我们的控制器编写一些单元测试。我们有以下简单的控制器 public class ClientController : Controller { [HttpPost] public ActionResult Create(Client client, [DataSourceRequest] DataSourceRequest request) { if (ModelState.IsValid) { clien

我正在为我们的控制器编写一些单元测试。我们有以下简单的控制器

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
方法中删除,则测试成功通过。非常感谢您的帮助。

中的一个快速峰值显示Kendo.Web.Mvc.dll是根据System.Web.Mvc 3.0版构建的。您的测试项目可能引用了较新版本的ASP.NET MVC(4.0),因此在运行时对
System.Web.MVC
成员的任何调用都会导致错误,因为无法解析这些成员。在您的特定情况下,对KendoUI MVC扩展方法
ToDataSourceResult()
的调用以及随后对
ModelState.IsValid
的调用是罪魁祸首

这一切在应用程序中正常工作的原因是,默认情况下,您的项目被配置为Visual Studio ASP.NET MVC项目模板的一部分,以便运行时以最新版本的ASP.NET MVC为目标。您可以通过在其App.config文件中添加相同的运行时绑定信息来修复测试项目:

<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>


我希望这能有所帮助。

非常感谢……我自己永远不会得出这个结论。这个答案救了我一天!