Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq using ReturnsAsync and modify It.IsAny input parameter

Tags:

c#

moq

When using ReturnsAsync, we could only get it to return a new object. Is there a better / more correct way to write the code below?

In this example, we have some sort of repository, and our implementation takes in an object of type Thing that has an Id (we want to pretend that our db set the Id) property:

var repo = new Mock<IRepositoryOfThings>();

//Is there a better way to do this perhaps using ReturnsAsync??
repo.Setup(r => r.Add(It.IsAny<Thing>())).Returns(
    (Thing x) =>
    {
        var tcs = new TaskCompletionSource<Thing>();
        x.Id = Guid.NewGuid().ToString();
        tcs.SetResult(x);
        return tcs.Task;
    });

Thanks!

like image 559
Greg Dietsche Avatar asked Aug 13 '26 17:08

Greg Dietsche


1 Answers

This is the best I could find:

var repo = new Mock<IRepositoryOfThings>();

repo.Setup(r => r.Add(It.IsAny<Thing>())).Returns(
    (Thing x) =>
    {
        x.Id = Guid.NewGuid().ToString();
        return Task.FromResult(x);
    });

It's effectively the same as your answer but only very slightly shorter.

like image 67
JustinHui Avatar answered Aug 16 '26 16:08

JustinHui