vendredi 29 avril 2016

Moq callbase for async methods don't work

I have class which is mocked but in some cases I need to run original method

public virtual async Task<int> SaveChangesAsync(string userId)
{
    try
    {
        TrackChanges(userId);//sets some fields
        return await db.SaveChangesAsync();
    }
    catch (Exception e)
    {
        LogSaveValidationFailed(e);
        throw;
    }
}

I have tried CallBase = true, but it don't work for async methods, also tried workaround with CallBack...

var db = new Mock<DbContext>();
db.CallBase = true;
db.Setup(x => x.SaveChangesAsync(It.IsAny<string>())).ReturnsAsync(1).Callback((string user) =>
{
    db.Object.SaveChanges(user);
});

...it returns value bud never call callback. Everything works normal method but doesn't work with async. What can I do to make it work with Moq, or it's better just refactor a bit and move TrackChanges from async method to normal?

Aucun commentaire:

Enregistrer un commentaire