awj*_*awj 5 c# unit-testing dynamic
给定以下 WebAPI 方法:
public IHttpActionResult GetDeliveryTypes()
{
return Ok(... .Select(dt => new { Id = dt.Id, Name = dt.Name }));
}
Run Code Online (Sandbox Code Playgroud)
在哪里
typeof(Id) = long
typeof(Name) = string
Run Code Online (Sandbox Code Playgroud)
在单元测试时,我如何
断言内容是否符合我的预期?例如,以下断言失败
var contentResult = response as OkNegotiatedContentResult<IEnumerable<dynamic>>;
Assert.IsNotNull(contentResult);
Run Code Online (Sandbox Code Playgroud)将此IEnumerable<dynamic>结果减少为IEnumerable<long>以便我可以验证它是否包含预期的值序列?
我已经将该InternalsVisibleTo属性添加到 AssemblyInfo。
1.从以下几件事开始:
response.GetType().GetGenericTypeDefinition() == typeof(OkNegotiatedContentResult<>)
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以从此处继续类型调查。
2.第二点的解决方案很简单:
dynamic response = controller.GetDeliveryTypes();
Assert.True(response.GetType().GetGenericTypeDefinition() == typeof(OkNegotiatedContentResult<>));
var content = (IEnumerable<dynamic>)response.Content;
var ids = content.Select(i => i.Id).ToList();
Run Code Online (Sandbox Code Playgroud)
如果测试位于单独的程序集中,则添加[assembly: InternalsVisibleTo("TestAssembly")]为作为内部生成的匿名类型。