lundi 1 août 2016

How to return passed parameters in an async method with Moq in unit tests?

I am struggeling with a problem of how to use the Moq-Setup-Return construct.

First my setting:

Some repository of type IRepository-Interface has to implement the StoreAsync-Method that returns a StoreResult object with the stored entity as property included.

using System.Threading.Tasks;
using Moq;
using Xunit;

namespace Tests
{
    public class Entity { }

    public class StoreResult
    {
        public Entity Entity { get; set; }
    }

    public interface IRepository
    {
        Task<StoreResult> StoreAsync(Entity entity);
    }

    public class Tests
    {
        [Fact]
        public void Test()
        {
            var moq = new Mock<IRepository>();
            moq.Setup(m => m.StoreAsync(It.IsAny<Entity>())).Returns(e => Task.FromResult<Task<StoreResult>>(new StoreResult {Entity = e}));
        }
    }
}

Now I try to write a Mock-Objekt for the IRepository-Interface, but I do not know how to code the Return-Statement so that the StoreResult-Object includes the entity given as parameter to the StoreAsync-Function.

I read about this topic in Moq ReturnsAsync() with parameters and MOQ: Returning value that was passed into a method.

I have tried

moq.Setup(m => m.StoreAsync(It.IsAny<Entity>()))
     .ReturnsAsync(entity => new StoreResult {Entity = entity});

with the error statement "Cannot convert lambda expression to type "StoreResult", because it is not a delegate type.

And with the same error message I tried

moq.Setup(m => m.StoreAsync(It.IsAny<Entity>()))
    .Returns(e => Task.FromResult<Task<StoreResult>>(new StoreResult {Entity = e}));

I am using a .NET Core xUnit environment with Moq 4.6.36-alpha

Thank you for your help.

Aucun commentaire:

Enregistrer un commentaire