How to use setup of a mocked anonymous type?

前端 未结 2 617
孤街浪徒
孤街浪徒 2021-01-14 11:04

I have the following repository:

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


        
相关标签:
2条回答
  • 2021-01-14 11:25

    A few implementation bugs that won't be picked up by the original solution:

    new {Activated = true, Enabled = false}
    new {Activated = true, Enabled = true, Extra = "I'm not meant to be here!"}
    new {Activated = true, Enabled = "true"}
    

    Depending on the complexity of your IReportingRepository GetReports method implementations it may be worth considering verifying the anonymous type's property values and value types are as expected and that only exactly the properties expected are present.

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

    Where the IsAnonymousType method is:

    private static object IsAnonymousType(object expected)
    {
        return Match.Create(
            (object actual) =>
            {
                if (expected == null)
                {
                    if (actual == null)
                        return true;
                    else
                        return false;
                }
                else if (actual == null)
                    return false;
    
                var expectedPropertyNames = expected.GetType().GetProperties().Select(x => x.Name);
                var expectedPropertyValues = expected.GetType().GetProperties().Select(x => x.GetValue(expected, null));
                var actualPropertyNames = actual.GetType().GetProperties().Select(x => x.Name);
                var actualPropertyValues = actual.GetType().GetProperties().Select(x => x.GetValue(actual, null));
    
                return expectedPropertyNames.SequenceEqual(actualPropertyNames)
                    && expectedPropertyValues.SequenceEqual(actualPropertyValues);
            });
    }
    
    0 讨论(0)
  • 2021-01-14 11:43

    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});
    

    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");
            });
    }    
    
    0 讨论(0)
提交回复
热议问题