How to Mock Asynchronous Methods in JustMock?

1.7k views Asked by At

I am new in Mocking. I am trying to mock my dbContext using JustMock. I am using Entity Framework 6. In Entity Framework 6 some features are asynchronous. I am successfully mock synchronous methods and my test is successfully pass. But I am stuck in asynchronous methods. My test still pass after i put wrong Assert.

Here is my Code :

Base Repository :

public class BaseRepository<T> : IRepositoryBase<T> where T : class, IEntity, new()
{
    protected readonly DbContext InnerDbContext;
    protected DbSet<T> InnerDbSet; 

    public BaseRepository(DbContext innerDbContext)
    {
        InnerDbContext = innerDbContext;
        InnerDbSet = InnerDbContext.Set<T>();
    }

    public virtual void Add(T entity)
    {
        InnerDbSet.Add(entity);
    }

    public virtual Task<T> FindAsync(long id)
    {
        return InnerDbSet.FirstOrDefaultAsync(x => x.Id == id && !x.IsDelete);
    }
}

DbContext :

public class TimeSketchContext : DbContext
{
    public DbSet<EmployeeSkill> EmployeeSkill { get; set; }
}

Test :

public class BaseRepositoryTest
{
    readonly TimeSketchContext _mockDataContext = Mock.Create<TimeSketchContext>();
    private  BaseRepository<EmployeeSkill> _repository;
    public BaseRepositoryTest()
    {
        _repository = new BaseRepository<EmployeeSkill>(_mockDataContext);
    }

    [Fact]
    public void Add_Should_Call_Once()
    {
        _repository.Add(Arg.IsAny<EmployeeSkill>());
        Mock.Assert(() => _mockDataContext.Set<EmployeeSkill>().Add(Arg.IsAny<EmployeeSkill>()), Occurs.Once());
    }

    [Fact]
    public async void Find_Should_Call_Once()
    {
        await _repository.FindAsync(Arg.AnyInt);
        Mock.Assert(() => _mockDataContext.Set<EmployeeSkill>().LastOrDefault(x => x.Id == Arg.AnyInt && !x.IsDelete), Occurs.Once());
        // This Test Will be fail Because my _repository.FindAsync is call FirstOrDefaultAsync. But it is pass.
    }
}

I am using :

  • Visual Studio 2013 Ultimate
  • .NET 4.5.1
  • JustMock Q3 2013 (2013.3.1015.0)
  • XUnit
1

There are 1 answers

0
Stephen Cleary On

I suspect that your problem is due to async void. XUnit (I believe) supports async void tests only in v2 and higher.

I recommend you change your async void test to async Task.