如何使用嘲笑匿名类型的设置吗? [英] How to use setup of a mocked anonymous type?

查看:163
本文介绍了如何使用嘲笑匿名类型的设置吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下资料库:

interface IReportingRepository where T: Report
{
     IEnumerable<T> GetReports<T>(object constraints);
}

和我试图模拟出这个仓库作为呼叫:

and I am trying to mock out a call to this repository as:

var reportingRepostory = new Mock<IReportingRepository>();
                       reportingRepostory.Setup(x => 
                       x.GetReports<ServiceReport (Moq.It.IsAny<object>())).
                       Returns(new List<ServiceReport>(){Report1, Report2});



然而,而不是在

However instead of passing in

Moq.It.IsAny<object>()

我要通过匿名类型

new {Activated = true, Enabled = true}

让我可以设置我的期望,正确的匿名类型被使用。

so that I can setup my expectation that the correct anonymous type is used.

推荐答案

您可以使用自定义的匹配有一点反思的帮助:

You can use custom matchers with a bit of reflection help:

var reportingRepostory = new Mock<IReportingRepository>();
reportingRepostory
    .Setup(x => x.GetReports<ServiceReport>(HasProperties()))
    .Returns(new List<ServiceReport>(){Report1, Report2});



其中, HasProperties 方法按下述方式实现:

Where HasProperties method is implemented as follows:

private object HasProperties()
{
    return Match.Create(
        (object o)  =>
        {
            var properties = o.GetType().GetProperties();
            return properties.Any(p => p.Name == "Available")
                && properties.Any(p => p.Name == "Enabled");
        });
}    

这篇关于如何使用嘲笑匿名类型的设置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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