Moq中的设置方法,模糊调用

use*_*693 23 c# tdd moq

我正在尝试使用Moq来模拟界面:

public interface IMatchSetupRepository
{
    IEnumerable<MatchSetup> GetAll();
}
Run Code Online (Sandbox Code Playgroud)

我在做:

var matchSetupRepository = new Mock<IMatchSetupRepository>();
matchSetupRepository
    .Setup(ms => ms.GetAll())
    .Returns(null);
Run Code Online (Sandbox Code Playgroud)

但由于错误,它甚至无法编译:

错误CS0121:以下方法或属性之间的调用不明确:'Moq.Language.IReturns <Data.Contract.IMatchSetupRepository,System.Collections.Generic.IEnumerable <Data.Model.MatchSetup >>.返回(System.Collections.Generic .IEnumerable <Data.Model.MatchSetup>)'和'Moq.Language.IReturns <Data.Contract.IMatchSetupRepository,System.Collections.Generic.IEnumerable <Data.Model.MatchSetup >>.返回(System.Func <System.Collections .Generic.IEnumerable <Data.Model.MatchSetup >>)"

我正在使用:

Moq.dll,v4.0.20926

And*_*ker 40

试试通用版本Returns:

var matchSetupRepository = new Mock<IMatchSetupRepository>();
matchSetupRepository
    .Setup(ms => ms.GetAll())
    .Returns<IEnumerable<MatchSetup>>(null);
Run Code Online (Sandbox Code Playgroud)

要么:

var matchSetupRepository = new Mock<IMatchSetupRepository>();
matchSetupRepository
    .Setup(ms => ms.GetAll())
    .Returns((IEnumerable<MatchSetup>)null);
Run Code Online (Sandbox Code Playgroud)

代替.因为您传递函数null(并且有两个重载Returns),编译器不知道您的意思是哪个重载,除非您将参数转换为正确的类型.

  • 是的,Moq非常棒! (2认同)