代码之家  ›  专栏  ›  技术社区  ›  superninja

Moq-无法从x转换为System.Func<x>

  •  0
  • superninja  · 技术社区  · 5 年前

     public JsonSerializerSettings createSerializerSettingsUsingRequest(Request request)
            {
    
                var serializerSettings = new JsonSerializerSettings()
                {
                    ContractResolver = new Utilities.CustomContractResolver(false, request.text)
                };
                return serializerSettings;
            }
    

    我就是这样嘲笑:

     _service = new Mock<IService>();
     _service.Setup(x => x.createSerializerSettingsUsingRequest(It.IsAny<Request>()))
                                    .Returns<JsonSerializerSettings>(new JsonSerializerSettings { ContractResolver = new Utilities.CustomContractResolver(false, null) });
    

    但错误显示

    无法从“Newtonsoft.Json.JsonSerializerSettings”转换为 System.Func<Newtonsoft.Json.JsonSerializerSettings, Newtonsoft.Json.JsonSerializerSettings>

    有人知道如何恰当地嘲笑它吗?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Nkosi    5 年前

    删除泛型参数。您试图调用的重载不会执行您认为它会执行的操作。

    var settings = new JsonSerializerSettings { 
        ContractResolver = new Utilities.CustomContractResolver(false, null) 
    };
    _service
        .Setup(x => x.createSerializerSettingsUsingRequest(It.IsAny<Request>()))
        .Returns(settings);
    

    如果您试图复制原始方法的行为,则可以访问传递的参数。

    例如

    _service
        .Setup(x => x.createSerializerSettingsUsingRequest(It.IsAny<Request>()))
        .Returns<Request>(request => new JsonSerializerSettings { 
            ContractResolver = new Utilities.CustomContractResolver(false, request.text) 
        });