0

我尝试使用 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 上使用通用方法来重构,但我真的很想知道我做错了什么。

最好的问候拉斯穆斯

4

1 回答 1

0

问题是 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);
}
于 2012-05-07T18:55:13.287 回答