c# - 在 ASP.NET MVC 中测试时如何访问 JsonResult 数据

标签 c# json asp.net-mvc-3 unit-testing

我在 C# mvc Controller 中有这段代码:

[HttpPost]
    public ActionResult Delete(string runId)
    {
        if (runId == "" || runId == null)
        {
            return this.Json(new { error = "Null or empty params" });
        }
        try
        {
            int userId = (int)Session["UserId"];
            int run = Convert.ToInt32(runId);

            CloudMgr cloud = new CloudMgr(Session);
            cloud.DeleteRun(userId, run);

            return this.Json(new { success = true });
        }
        catch (Exception ex)
        {
            return this.Json(new { error = ex.ToString() });
        }
    }

如何访问 ControllerTest 中的 Json“错误”字段以检查它是否为空?

[TestMethod]
    public void DeleteWrongParam()
    {
        WhatIfController controller = new WhatIfController();
        controller.ControllerContext = 
        TestUtils.CreateMockSessionControllerContext().Object as ControllerContext;

        JsonResult result = controller.DeleteWhatIf(null) as JsonResult;

Assert.IsNotNull(result.Data.error); 是我想要做的。有任何想法吗?谢谢。

最佳答案

JavaScriptSerializer 适用于字符串和静态类型。在这里,您将匿名类型创建为 Json(new { success = true })。这种情况,你最好使用动态类型。

JsonResult result = controller.DeleteWhatIf(null) as JsonResult;
dynamic dresult = result.Data;
Assert.IsTrue(dresult.succes);

您需要导入 Microsoft.CSharp dll 来测试项目。

如果测试和你的 Controller 在不同的程序集中,你需要让测试程序集成为 Controller 程序集的“ friend ”程序集,像这样:

[程序集:InternalsVisibleTo("测试项目程序集名称")]

关于c# - 在 ASP.NET MVC 中测试时如何访问 JsonResult 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232470/

相关文章:

python - 如何使用嵌套的 Python 字典和 D3.js?

c# - 具有泛型的结构图配置

c# - 如何从 C# 控制台应用程序向使用表单例份验证的 ASP.NET WebAPI 进行身份验证?

json - Go中如何自定义JSON编码输出?

c# - 将 ViewModel 数据返回到 Javascript 函数 MVC 4?

asp.net-mvc-3 - ASp.NET MVC 3.0 调用通用扩展 html 帮助器方法时出错

c# - 在 StackService.Redis 客户端方法 Store() 上导致 stackoverflow 的递归对象

c# - 从 bin 以外的文件夹加载程序集

c# - 使用 C# 提高大数据导入 SQLite 的性能

c# - 定时器与 While 循环——内存使用