使用Kendo UI在MVC4中测试控制器操作

Ale*_*lex 6 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)
        {
            clientRepo.InsertClient(client);
        }

        return Json(new[] {client}.ToDataSourceResult(request, ModelState));
    }
}
Run Code Online (Sandbox Code Playgroud)

单元测试如下:

[Test]
public void Create()
{
        // Arrange
        clientController.ModelState.Clear();

        // Act
        JsonResult json = clientController.Create(this.clientDto, this.dataSourceRequest) as JsonResult;

        // Assert
        Assert.IsNotNull(json);

}
Run Code Online (Sandbox Code Playgroud)

并使用以下代码伪造控制器上下文:

 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
    {

    }


}
Run Code Online (Sandbox Code Playgroud)

Create控制器操作尝试调用该ToDataSourceResult方法时发生异常.

System.EntryPointNotFoundException : Entry point was not found.
Run Code Online (Sandbox Code Playgroud)

调试显示ModelState内部字典在单元测试中是空的(而不是在标准上下文中运行时).如果ModelStateToDataSourceResult方法中删除,则测试成功通过.任何帮助深表感谢.

Kev*_*ock 5

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

这一切在您的应用程序中正常运行的原因是因为您的项目默认配置为Visual Studio ASP.NET MVC项目模板的一部分,以重定向程序集绑定,以便运行时针对最新版本的ASP.NET MVC assemblied.您可以通过在其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>
Run Code Online (Sandbox Code Playgroud)

我希望有所帮助.