我需要一些帮助模拟和测试我的课程。我尝试了各种方法,觉得这是我最接近的方法。 // 1和// 2是两次单独的尝试。
方法一没有错误,但我不知道如何使用Assert
调用实际测试任何内容。
尝试2有错误消息
无法实例化类的代理:RentalsRated.Data.RentalsDBContext。
测试
[Fact]
public void RepoUA_GetAll()
{
var users = new List<UserAccount> {
new UserAccount { Id = "idstring1", Username = "username1"},
new UserAccount { Id = "idstring2", Username = "username2" },
new UserAccount { Id = "idstring3", Username = "username3" },
}.AsQueryable();
var mockContext = new Mock<RentalsDBContext>();
var mockSet = new Mock<DbSet<UserAccount>>();
mockSet.As<IQueryable<UserAccount>>().Setup(m => m.Provider).Returns(users.Provider);
mockSet.As<IQueryable<UserAccount>>().Setup(m => m.Expression).Returns(users.Expression);
mockSet.As<IQueryable<UserAccount>>().Setup(m => m.ElementType).Returns(users.ElementType);
mockSet.As<IQueryable<UserAccount>>().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator());
mockContext.Setup(m => m.Set<UserAccount>()).Returns(mockSet.Object).Verifiable();
//1
Mock<IRentalsRepository<UserAccount>> MockRepo = new Mock<IRentalsRepository<UserAccount>>();
MockRepo.Setup(m => m.GetAll()).Returns(users);
//2
var testClass = new RentalsRepository<UserAccount>(mockContext.Object);
var result = testClass.Get("idstring2");
Assert.Equal("idstring2", result.Id);
}
回购
public class RentalsRepository<T> : IRentalsRepository<T> where T : BaseClass
{
private readonly RentalsDBContext _Context;
private DbSet<T> entities;
string errorMessage = string.Empty;
public RentalsRepository(RentalsDBContext _Context)
{
this._Context = _Context;
entities = _Context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return entities.AsEnumerable();
}
}
上下文
public class RentalsDBContext : DbContext
{
public RentalsDBContext(DbContextOptions<RentalsDBContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public virtual DbSet<UserAccount> UserAccounts { get; set; }
public virtual DbSet<Rating> Ratings { get; set; }
public virtual DbSet<PropertyAddress> PropertyAddresses { get; set; }
public virtual DbSet<Town> Towns { get; set; }
public virtual DbSet<County> Countys { get; set; }
public virtual DbSet<RatingImage> RatingImages { get; set; }
}
答案 0 :(得分:1)
您将成为RentalsDBContext
的默认构造函数,因为Moq无法使用其当前构造函数实例化该类。
public class RentalsDBContext : DbContext {
public RentalsDBContext() : base() { }
public RentalsDBContext(DbContextOptions<RentalsDBContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
//...other code removed for brevity
}