mocking a method with an anonymous type argument

只愿长相守 提交于 2019-12-11 18:43:52

问题


I have the following code:

var connector = new Mock<IConector>();

connector
    .Setup(cn => cn.listar("FetchEstandar", new Estandar(), new {Id = 1}))
    .Returns(new List<Estandar>{ new Estandar {Id = 1} });

 var entidad = connector.Object
     .listar("FetchEstandar", new Estandar(), new {Id = 1});

when I call listar on the connector Object, I get an "Expression Cannot Contain an Anonymouse Type" error. I've tried with rhino mocks and moq.

Is there any way I can mock this method? am I doing something wrong? alternatively, I could ignore this parameter but I don't know how. I really just need to test the value of the first parameter and ignorearguments works but I have no idea whether or how I can get this value if I use it


回答1:


I do not know if this is the only way to match an anonymous object but it can be done using It.Is<>() and reflection

public class Estandar {
    public int Id { get; set; }
}

public interface IConector {
    IEnumerable<Estandar> listar(string name, Estandar estandar, object key);   
}


[TestMethod]
public void CheckAnonymous() {

    var connector = new Mock<IConector>();

    connector.Setup(cn => cn.listar("FetchEstandar",
                                    It.IsAny<Estandar>(),
                                    It.Is<object>(it => MatchKey(it, 1))))
             .Returns(new List<Estandar> { new Estandar { Id = 1 } });

    var entidad = connector.Object.listar("FetchEstandar", new Estandar(), new { Id = 1 });

    Assert.AreEqual(1, entidad.Count());

}

public static bool MatchKey(object key, int soughtId) {
    var ret = false;
    var prop = key.GetType().GetProperty("Id");
    if (prop != null) {
        var id = (int)prop.GetValue(key, null);
        ret = id == soughtId;
    }
    return  ret;
}


来源:https://stackoverflow.com/questions/12927118/mocking-a-method-with-an-anonymous-type-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!