mardi 6 novembre 2018

Getting expcetion with Moq when trying to test Task

I'm trying to use Moq (4.10) on async calls but I cannot get the hang of it

Search on how to do so and found answers which I've tried but I cannot make it to work .

This is my test

 public class Test
 {
        [Fact]
        public void Test_Create()
        {
            var repositoryMock = new Mock<IRepository>();
        repositoryMock.Setup(repo => repo.CreateAsync(It.IsAny<Aggregate >())).Returns(Task.CompletedTask); 

/// => also tried this 
/// repositoryMock.Setup(repo => repo.CreateAsync(It.IsAny<Aggregate >())).Returns(Task.FromResult(false))); 

        var useCase = new CreateUseCase(repositoryMock.Object);

        Task.Run(async () => { await useCase.HandleAsync(new CreateRequest()); });

        repositoryMock.VerifyAll();
        }
}

Getting this exception

Moq.MockException: 'The following setups on mock 'Mock<.Repository.IRepository:00000001>' were not matched: IRepository repo => repo.CreateAsync(It.IsAny())

The repo looks like this

public interface IRepository 
{
    Task CreateAsync(Aggregate aggregate);
}

The UseCase

    public class CreateUseCase : IUseCaseHandler<CreatRequest>
    {

        private IRepository _repository;


        public CreateUseCase (IRepository repository)
        {
            _repository= repository?? throw new System.ArgumentNullException(nameof(repository));
        }


            public async Task HandleAsync(CreateRequest request, CancellationToken? cancellationToken = null)
            {
                Aggregateaggregate = new Aggregate();

                aggregate.Create();

                await _repository.CreateAsync(aggregate);
            } 
    }

Aucun commentaire:

Enregistrer un commentaire