我是 Mocking 的新手。我正在尝试使用 JustMock 模拟我的 dbContext。我正在使用 Entity Framework 6。在 Entity Framework 6 中,一些功能是异步的。我成功地模拟了同步方法,并且我的测试成功通过了。但我被困在异步方法中。在我输入错误的 Assert 后,我的测试仍然通过。
这是我的代码:
基础存储库:
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);
}
}
数据库上下文:
public class TimeSketchContext : DbContext
{
public DbSet<EmployeeSkill> EmployeeSkill { get; set; }
}
测试 :
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.
}
}
我在用 :
- Visual Studio 2013 终极版
- .NET 4.5.1
- JustMock 2013 年第三季度 (2013.3.1015.0)
- XUnit