romantitov / MockQueryable

Mocking Entity Framework Core operations such ToListAsync, FirstOrDefaultAsync etc
MIT License
785 stars 76 forks source link

Mocking AddAsync #61

Closed AdisonCavani closed 2 years ago

AdisonCavani commented 2 years ago

I need to mock AddAsync(obj) function. I have seen this stackoverflow topic, but proposed code:

mockWebJobDbSet
    .Setup(_ => _.AddAsync(It.IsAny<WebJobStatus>(), It.IsAny<System.Threading.CancellationToken>()))
    .Callback((WebJobStatus model, CancellationToken token) => { webjobstatusList.Add(model); })
    .Returns((WebJobStatus model, CancellationToken token) => Task.FromResult((EntityEntry<WebJobStatus>)null));

will return null EntityEntry<WebJobStatus> which will cause to fail my unit test.

Function I want to test:

Url obj = new()
{
    FullUrl = url
};

var savedObj = await _context.Url.AddAsync(obj);

return savedObj.Entity.Id

Error: savedObj is null

romantitov commented 2 years ago

Hello @AdisonCavani thank you for your feedback. savedObj is null because in .Returns((WebJobStatus model, CancellationToken token) => Task.FromResult((EntityEntry<WebJobStatus>)null)); you defined to return null for result of any AddAsync operation. You need to receive result from AddAsync not equal to null you have to define it in .Returns... To make it work you can just do it according to the answer.