简体   繁体   English

Moq 使用 ReturnsAsync 并修改 It.IsAny 输入参数

[英]Moq using ReturnsAsync and modify It.IsAny input parameter

When using ReturnsAsync, we could only get it to return a new object.使用 ReturnsAsync 时,我们只能让它返回一个新对象。 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:在这个例子中,我们有某种存储库,我们的实现接受一个具有 Id(我们想假设我们的 db 设置了 Id)属性的 Thing 类型的对象:

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!谢谢!

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.它实际上与您的答案相同,但只是稍微短了一点。

You can just initialize an instance of Thing and return that instance in your setup.您可以只初始化 Thing 的一个实例并在您的设置中返回该实例。

   var repo = new Mock<IRepositoryOfThings>();
   var thing = new Thing
   {
       Id = Guid.NewGuid().ToString()
   };
   repo.Setup(r => r.Add(It.IsAny<Thing>())).ReturnsAsync(thing);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM