Home > OS >  Moq: Manipulate passed param does not work
Moq: Manipulate passed param does not work

Time:07-07

I have something like this:

MyMock
.Setup(m => m.MyMethodAsync(It.IsAny<Stream>()))
.Returns((Stream outStream) =>
{
   outStream = new MemoryStream(Encoding.UTF8.GetBytes("this is the content"));
   return Task.CompletedTask;
});

this can be compiled and executed. I can see the debugger running the code. But the caller of this method do not get the value of the Stream. What do i miss?

Edit1:

Change Returns to Callback has the same behavior

.Callback((MT365ReceiveResult result, Stream outStream) =>
{
    outStream = new MemoryStream(Encoding.UTF8.GetBytes("this is the content"));
});

CodePudding user response:

The code of the sample does not use the Stream that is provided by the caller of the method, but assigns a new MemoryStream to the parameter. As the parameter is not marked with ref or out, this reassignment is only valid in the method, but not outside.

I suppose, you want to write a value to the Stream that is provided by the caller. You can do this with the following code:

MyMock
  .Setup(m => m.MyMethodAsync(It.IsAny<Stream>()))
  .Returns((Stream outStream) =>
  {
    var bytes = Encoding.UTF8.GetBytes("this is the content");
    outStream.Write(bytes, 0, bytes.Length);
    return Task.CompletedTask;
  });
  • Related