【问题标题】:using Moq and generic type boxing issue使用起订量和通用类型装箱问题
【发布时间】:2012-05-07 18:32:28
【问题描述】:

我尝试使用 Moq 和 nunit 制作通用辅助方法,如下所述

public void PrepareWebRequest<T>() where T : new()
    {            
        httpCommunicator = new Mock<IHttpCommunicator>();
        httpCommunicator.Setup(x => x.Post(It.IsAny<Object>(),
                                                      It.IsAny<string>())).Throws<T>();

        service = new ApiClient(httpCommunicator.Object);
    }

但这会导致以下错误:

类型“T”不能用作泛型类型或方法“Moq.Language.IThrows.Throws()”中的类型参数“TException”。没有从 'T' 到 'System.Exception' 的装箱转换或类型参数转换。

我知道这可以通过不在 Moq 上使用泛型方法来重构,但我真的很想知道我做错了什么。

最好的问候 拉斯穆斯

【问题讨论】:

    标签: unit-testing tdd moq


    【解决方案1】:

    问题是 Where 子句中缺少异常。应该是

    public void PrepareWebRequest<T>() where T : Exception, new()
    {            
        httpCommunicator = new Mock<IHttpCommunicator>();
        httpCommunicator.Setup(x => x.Post(It.IsAny<Object>(),
                                                      It.IsAny<string>())).Throws<T>();
    
        service = new ApiClient(httpCommunicator.Object);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      相关资源
      最近更新 更多