Moq使用Mock.of返回对象的值



我需要模拟对象中方法的返回值。我有这样的东西:

var mock = Mock.Of<IExample>( x => x.GetAll() == new List<IOtherExample>()) ;

但我犯了一个错误。如果我使用GetAll作为属性,它会起作用:

var mock = Mock.Of<IExample>( x => x.GetAll == new List<IOtherExample>()) ;

我知道我可以使用新的模拟,设置和返回这样做:

mock.Setup(x => x.GetAll()).Returns(new List<IOtherExample>());

但我想学习如何使用Mock.Of.

错误看起来像这样:

 Expression of type 'System.Collections.Generic.List' cannot be used for parameter of type 'System.Collections.Generic.IList' of method 'Moq.Language.Flow.IReturnsResult' Returns(System.Collections.Generic.IList)'

再次请记住,如果GetAll是一个属性,它是有效的。

谢谢。

public interface IExample : IGenericExample<IOtherExample>
{
}
public interface IGenericExample<T>
{
   IList<T> GetAll()
}

由于代码格式的原因,无法将其作为注释发布:

void Main()
{   
    var t = Mock.Of<IExample>(x => x.GetAll() == new List<IOtherExample>());
    t.GetAll().Dump();
}
// Define other methods and classes here
public interface IOtherExample
{
}
public interface IExample : IGenericExample<IOtherExample>
{
}
public interface IGenericExample<T>
{
   IList<T> GetAll();
}

这适用于我的LINQPad,我使用的是Moq4.0。我是不是错过了什么?

var example = Mock.Of<IExample>();
Mock.Get(example).Setup(x => x.GetAll()).Returns(new List<IOtherExample>());

也就是说,我认为Mock.Of<>在语义上有点倒退。它表示返回的对象具有mock,而new Mock<>返回具有实际实例的mock对象。

我发现这个设置比上面的片段更有意义。

var exampleMock = new Mock<IExample>();
exampleMock.Setup(x => x.GetAll()).Returns(new List<IOtherExample>());

稍后,当需要将实例作为参数或断言传递时,使用exampleMock.Object就足够简单了。

最新更新