Reputation: 133
I currently have code like:
var fieldBoundary = Properties.Resources.TestFieldBoundary;
httpClient.Setup(
x =>
x.GetAsync(It.Is<Uri>(url => url.AbsoluteUri == APIUrl.AbsoluteUri + <my url>)))
.Returns(
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(Encoding.Default.GetString(fieldBoundary))
}));
The first time through, using this mock http client I get the response that I expect. However when I call the same URL with the same mock object a second time I get a successful response but the response is an empty string or zero length byte array. Ideas on how this could be Moq'd differently?
Upvotes: 5
Views: 507
Reputation: 247183
Change the Returms
to use a function instead.
httpClient
.Setup(x => x.GetAsync(It.Is<Uri>(url => url.AbsoluteUri == APIUrl.AbsoluteUri + <my url>)))
.Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) {
Content = new StringContent(Encoding.Default.GetString(fieldBoundary))
})
);
it will call the function every time you make a call to the mocked method instead of returning the same instance on repeated calls. That is why when you made the call the second time the string content stream pointer was already at the end.
Upvotes: 5