Moq Verifiable使用LINQ语法

时间:2014-03-03 18:24:25

标签: c# linq mocking moq

我正在使用Moq和NUnit为Windows服务创建一些测试。我有以下内容:

mockPushService = Mock.Of<IPushService>(m => 
    m.SendPushNotification(It.IsAny<UserDevice>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>())); // Breaks.

mockMailService = Mock.Of<IEmailService>(m =>
    m.SendMessage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()) &&
    m.ThrowErrors == true);

mockMailService正在使用LINQ语法,因为这些方法不是无效的。但是,mockPushService无效,因为它是一种void方法。我知道我应该使用Verifiable,但我不确定如何使用这种语法。

为了更清楚,我得到了这个编译时错误:

Cannot convert lambda expression to delegate type 'System.Func<SurgeHub.Domain.Services.IPushService,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type

Cannot implicitly convert type 'void' to 'bool'

我该如何使这项工作?谢谢。

2 个答案:

答案 0 :(得分:3)

我一直使用Moq Setup方法。所以你的第一个例子就会变成;

var push = new Mock<IPushService>();
push.Setup(a => a.SendPushNotification(It.IsAny<UserDevice>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>()));

同样,你的第二个例子,无论如何都在运作,如下(注意我假设的回报是一个bool)

var mail = new Mock<IEmailService>();
mail.Setup(a => a.SendMessage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(true);
mail.SetupProperty<bool>(a => a.ThrowErrors, true);

答案 1 :(得分:0)

你不能使用它,因为重载期望你的方法总是返回bool。我不理解很多 Of(T)方法,但我想你应该使用设置normaly。