如何用Moq模拟HttpRequestMessage

时间:2019-01-22 21:18:30

标签: c# asp.net moq

我正在使用网络Api。这是一个ASP.NET应用程序。我需要为HttpRequestMessage类的CreateResponse(HttpStatusCode statusCode,T值)方法创建一个模拟。但是每次我执行测试并获得异常

Test Name:  RHT.Tests.Controllers.AccountControllerTests.Can_login_with_valid_credentials
Test FullName:  RHT.Tests.Controllers.AccountControllerTests.Can_login_with_valid_credentials
Test Source:    Controllers\AccountControllerTests.cs : line 23
Test Outcome:   Failed
Test Duration:  0:00:01.028

Result StackTrace:  
at Moq.Mock.ThrowIfSetupExpressionInvolvesUnsupportedMember(Expression setup, MethodInfo method) in C:\projects\moq4\src\Moq\Mock.cs:line 755
   at Moq.Mock.SetupNonVoidPexProtected(Mock mock, LambdaExpression expression, Condition condition) in C:\projects\moq4\src\Moq\Mock.cs:line 433
   at Moq.PexProtector.Invoke[T1,T2,T3,TResult](Func`4 function, T1 arg1, T2 arg2, T3 arg3) in C:\projects\moq4\src\Moq\PexProtector.cs:line 38
   at Moq.Mock.SetupNonVoid(Mock mock, LambdaExpression expression, Condition condition) in C:\projects\moq4\src\Moq\Mock.cs:line 421
   at Moq.Mock`1.Setup[TResult](Expression`1 expression) in C:\projects\moq4\src\Moq\Mock.Generic.cs:line 317
   at RHT.Tests.Controllers.AccountControllerTests.Can_login_with_valid_credentials() in C:\Users\ttong\source\repos\RedHawkTestPlan\RHT.Tests\Controllers\AccountControllerTests.cs:line 51
Result Message: System.NotSupportedException : Invalid setup on an extension method: m => m.CreateResponse<string>(HttpStatusCode.OK, "value")

测试

        Mock<IAuthProvider> auth = new Mock<IAuthProvider>();
        auth.Setup(m => m.CreateEncryptedCookieValue(
            It.IsAny<bool>(), It.IsAny<string>()))
            .Returns("my_ticket");

        Mock<HttpRequestMessage> req = new Mock<HttpRequestMessage>();
        req.Setup(m => m.CreateResponse(
            HttpStatusCode.OK, "value"))
            .Returns(new HttpResponseMessage(HttpStatusCode.OK));

测试方法具有3个模拟对象。但是只有HttpRequestMessage无法初始化。知道为什么它不起作用吗?

1 个答案:

答案 0 :(得分:0)

答案在错误消息中:

  

System.NotSupportedException:扩展方法上的无效设置

CreateResponse不是HttpRequestMessage类的方法,而是扩展方法。扩展方法不能被嘲笑,因为它们实际上是幕后的静态方法。