Creating a mock IHttpFilter to test Windows.Web.Http.HttpClient

I want to create a "mock" implementation IHttpFilterto test calls with Windows.Web.Http HttpClient. This is my SendRequestAsync method in implementation

 public IAsyncOperationWithProgress<HttpResponseMessage,HttpProgress> 
    SendRequestAsync(HttpRequestMessage request)
            {
                HttpResponseMessage response = new HttpResponseMessage(_statusCode);
                response.Content = _content;

                //This is the problematic part
                return AsyncInfo.Run<HttpResponseMessage, HttpProgress>(
                    (token, progress) => Task.Run<HttpResponseMessage>(
                        () => { return response; }));           
            }

In my testing method, I use it like this. It is also a way to use HttpClientthe application.

//This Throws an InvalidCastException
var result = await client.SendRequestAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.nomatter.com")));

But it throws an InvalidCastException

Result Message: Test method UnitTestLibrary1.UnitTest.TestHttp threw exception: 
System.InvalidCastException: Specified cast is not valid.
Result StackTrace:  
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at UnitTestLibrary1.UnitTest.<TestHttp>d__0.MoveNext() in c:\Users\****\UniversalPCLUnitTest\UnitTestLibrary1\UnitTest1.cs:line 40
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

I cannot understand why the exception is thrown. Has anyone encountered the same problem?

+4
source share
1 answer

There are two answers to this question.

, System.Net.HttpClient. ONCE , , Singleton.

HttpClient - , IE

public interface ICanGetHttpBodies{
    string AsString(Uri uri);
}

, , , :

[TestMethod, ExpectedException(typeof(ProgramException))]
public void MyMethod_WhenEmptyBody_ThrowsException()
{
    // Arrange 
    var emptyBody = "";
    var getBodyMock = new Mock<ICanGetHttpBodies>()
        .Setup(m => m.AsString(It.IsAny<Uri>())
        .Returns(emptyBody);

    // Act & Assert
}

, , HttpClient , (ICanGetHttpBodies), ( :))

, Visual Studio - "", / , HttpClient DateTime:

https://msdn.microsoft.com/en-us/library/hh549175.aspx

, , 1:)

-1

Source: https://habr.com/ru/post/1628544/


All Articles