本文介绍了FakeItEasy 和匹配的匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法匹配使用匿名类型的期望.我是 FakeItEasy 的新手,但不是嘲笑,并且想要一些关于匹配参数的正确方法的指导.我从这个线程中了解到(https://github.com/FakeItEasy/FakeItEasy/问题/532#issuecomment-135968467)谓词可以提取到方法".我创建了一个匹配 Func<object, bool> 的方法.名为 IsMatch 的签名以隐藏反射(类似于上面包含的 link#comment),并且 FakeItEasy 参数解析器仍然没有选择它.这是一个失败的测试.如何检查匿名类型?

I having trouble matching an expectation that uses anonymous types. I am new to FakeItEasy but not to mocking and would like some guidance on what is the proper way to match arguments. I understand from this thread (https://github.com/FakeItEasy/FakeItEasy/issues/532#issuecomment-135968467) that the "predicate can be extracted to a method". I have created a method that matches a Func<object, bool> signature named IsMatch to hide the reflection (similar to the link#comment included above) and the FakeItEasy argument parser still doesn't pick it up. Here is a failing test. How can I check the anonymous type?

using System;
using System.Collections.Generic;
using FakeItEasy;
using Xunit;

namespace UnitTests
{
    public class Tests
    {
    private Dictionary<string, object> _properties;

    [Fact]
    public void AnonymousTest()
    {
        string id = "123456ABCD";
        string status = "New Status";

        var fake = A.Fake<IRepository>();
        var logic = new BusinessLogic(fake);

        _properties = new Dictionary<string, object>()
        {
            {"Status__c", status},
            {"UpdatedOn__c", DateTime.Today},
            {"IsDirty__c", 1},
        };

        var expectation = A.CallTo(() => fake.UpdateDatabase(id, A<object>.That.Matches(anon => IsMatch(anon))));

        logic.ChangeStatus(id, status);

        expectation.MustHaveHappenedOnceExactly();
    }

    private bool IsMatch(object o)
    {
        foreach (var prop in _properties)
        {
            if (!o.GetType().GetProperty(prop.Key).GetValue(o).Equals(prop.Value))
                return false;
        }

        return true;
    }
}
public interface IRepository
{
    void UpdateDatabase(string id, object fields);
}

public class BusinessLogic
{
    private IRepository _repo;
    public BusinessLogic(IRepository repo)
    {
        _repo = repo;
    }

    public void ChangeStatus(string id, string status)
    {
        var fields = new
        {
            Status__c = status,
            UpdatedOn__c = DateTime.Today,
            IsDirty__c = true
        };
        _repo.UpdateDatabase(id, fields);
    }
}
}

推荐答案

@philipwolfe,你的测试结构在我看来很合适,所以我试了一下.当我改变时它通过

@philipwolfe, the structure of your test looked right to me, so I tried it out.It passes when I change

{"IsDirty__c", 1}

{"IsDirty__c", true}

匹配ChangeStatus方法中内置的对象.

to match the object built in ChangeStatus method.

这篇关于FakeItEasy 和匹配的匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 18:35