断言JsonResult包含匿名类型 [英] Asserting JsonResult Containing Anonymous Type

查看:164
本文介绍了断言JsonResult包含匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图单元测试我控制器返回JsonResult的一种方法。令我惊讶以下code没有工作:

I was trying to unit test a method in one of my Controllers returning a JsonResult. To my surprise the following code didn't work:

[HttpPost]
public JsonResult Test()
{
    return Json(new {Id = 123});
}

这是我如何测试它:

// Act
dynamic jsonResult = testController.Test().Data;

// Assert
Assert.AreEqual(123, jsonResult.Id);

断言抛出异常:

对象不包含定义为ID

我已经因为使用它解决如下:

I've since resolved it by using the following:

[HttpPost]
public JsonResult Test()
{
   dynamic data = new ExpandoObject();
   data.Id = 123;
   return Json(data);
}

我试图理解为什么不是第一个工作?这也似乎与基本什么,但一个匿名类型的工作。

I'm trying to understand why isn't the first one working ? It also seems to be working with basically anything BUT an anonymous type.

推荐答案

需要明确的是,您所遇到的具体问题是,C#动态不与非公开成员的工作。这是由设计,presumably劝阻之类的事情。由于作为LukLed指出,匿名类型是公开只能在同一组件(或更precise,匿名类型只被标记为内部,而不是公共),您正在运行到这一障碍。

To be clear, the specific problem you are encountering is that C# dynamic does not work with non-public members. This is by design, presumably to discourage that sort of thing. Since as LukLed stated, anonymous types are public only within the same assembly (or to be more precise, anonymous types are simply marked internal, not public), you are running into this barrier.

大概是干净的解决方案将是您可以使用 InternalsVisibleTo 。它可以让你的名字,可以访问其非公共成员另一个集会。用它来测试是主要的原因,它的存在之一。在你的榜样,你会在你的主项目的AssemblyInfo.cs中放置以下行:

Probably the cleanest solution would be for you to use InternalsVisibleTo. It allows you to name another assembly that can access its non-public members. Using it for tests is one of the primary reasons for its existance. In your example, you would place in your primary project's AssemblyInfo.cs the following line:

[assembly: InternalsVisibleTo("AssemblyNameOfYourTestProject")]

一旦你这样做,错误就会消失(我只是尝试它自己)。

Once you do that, the error will go away (I just tried it myself).

另外,你可以只用蛮力反思:

Alternatively, you could have just used brute force reflection:

Assert.AreEqual(123, jsonResult.GetType().GetProperty("Id").GetValue(jsonResult, null));

这篇关于断言JsonResult包含匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆