【问题标题】:Mocking async methods with optional parameters throws Expression is not a Property Access使用可选参数模拟异步方法会抛出 Expression is not a Property Access
【发布时间】:2020-04-21 16:42:06
【问题描述】:

我正在使用 Nuget 包 Moq (v4.13.1)

我试图模拟的类/方法具有以下接口:

public interface IAgendaService
{
    Task<IList<IMeeting>> GetRecentMeetingsMostRecentFirstAsync(
        IWho who,
        TimeSpan? timeSpan = null,
        int? maxNumberOfMeetings = null);
}

在我的测试方法中,我有以下代码来定义 Mock:

        Mock<IAgendaService> service = new Mock<IAgendaService>(MockBehavior.Strict);

        service.SetupGet(x =>
                x.GetRecentMeetingsMostRecentFirstAsync(
                    It.IsAny<IWho>(),
                    It.IsAny<TimeSpan?>(),
                    It.IsAny<int?>()))
            .Returns(Task.FromResult((IList<IMeeting>)new List<IMeeting>()));

当我运行测试时,service.SetupGet() 抛出以下异常:

测试方法 Agenda.Web.Tests.Controllers.HomeController.IndexTests.TestIndex 抛出异常: System.ArgumentException:表达式不是属性访问:x => x.GetRecentMeetingsMostRecentFirstAsync(It.IsAny(), It.IsAny(), It.IsAny()) 在 Moq.ExpressionExtensions.ToPropertyInfo(LambdaExpression 表达式) 在 Moq.Mock.SetupGet(Mock mock, LambdaExpression 表达式, Condition 条件) 在 Moq.Mock1.SetupGet[TProperty](Expression1 表达式)

我做错了什么?

【问题讨论】:

  • 你需要使用service.Setup()方法没有SetupGet

标签: c# unit-testing mocking moq


【解决方案1】:

您似乎使用了错误的方法来进行模拟设置。您应该使用Setup 方法,因为SetupGet 用于属性获取器。请尝试以下操作:

service.Setup(x =>
            x.GetRecentMeetingsMostRecentFirstAsync(
                It.IsAny<IWho>(),
                It.IsAny<TimeSpan?>(),
                It.IsAny<int?>()))
        .Returns((IList<IMeeting>)new List<IMeeting>()));

也没有必要使用Task.FromResult,因为它是一个模拟对象,所以没有任何异步发生。

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多