Sebastiaan Haverkate
Sebastiaan Haverkate

Reputation: 107

How to mock returning a memorystream multiple times?

I have this call to an external source that returns a FileResponse object that also contains a Stream object. To Mock it I use a MemoryStream object and that works as long as the test is focused on one item.

As the products to update can now come from 2 data sources I need to create a unit test that mocks sending 2 items to the external source. I have the following code:

_client.Setup(c => c.ApiSupplierProductPostAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())).ReturnsAsync(new FileResponse(200, null, new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(json))), null, null));

The problem I have is that when processing the second product the MemoryStream is at the end of the stream. How do I get the Setup to return a new MemoryStream every time it is called?

The string given to the method is the json body of the message send to the external source.

Upvotes: 1

Views: 53

Answers (0)

Related Questions