0

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

Rockstart
  • 2,337
  • 5
  • 30
  • 59
Nicolas Straub
  • 3,381
  • 6
  • 21
  • 42
  • 1
    Can you please post your `IConector.listar` method signature? Which moq version are you using? Because the version 3.1.416.3 doesn't throw any error when I execute your code. – nemesv Oct 17 '12 at 04:51
  • Moq 4.0.10827.0 is not throwing any errors either if I use 'IEnumerable listar(string name, Estandar estandar, object id);' as the signature for listar, however the setup will never match because the new Estandar() in the setup is not the same as the new Estandar when called. – AlanT Oct 17 '12 at 09:00
  • yeah, sorry, it does work but returns an empty list. – Nicolas Straub Oct 18 '12 at 01:14

1 Answers1

2

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;
}
AlanT
  • 3,627
  • 20
  • 28