我是单元测试的新手,我需要一些帮助。我首先使用代码和存储库模式。我有一个通用存储库,其中包含称为通用存储库的通用 CRUD 操作(请参阅打击)
public abstract class GenericRepository<T> where T : class
{
private HolidayDatabaseContext _dataContext;
private readonly IDbSet<T> _dbset;
protected GenericRepository(IDbFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
_dbset = DataContext.Set<T>();
}
protected IDbFactory DatabaseFactory
{
get;
private set;
}
protected HolidayDatabaseContext DataContext
{
get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
_dbset.Add(entity);
}
public virtual void Update(T entity)
{
_dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
_dbset.Remove(entity);
}
public virtual IEnumerable<T> Enumerable()
{
return _dbset.AsEnumerable<T>();
}
public virtual IQueryable<T> List()
{
return _dbset.AsQueryable<T>();
}
public virtual T GetSingleById(int id)
{
return _dbset.Find(id);
}
public void Save()
{
_dataContext.SaveChanges();
}
}
然后我将它继承到用户存储库中并创建了一些特定的方法。见下文
public class UserRepository : GenericRepository<User>, IUserRepository
{
public UserRepository(IDbFactory databaseFactory)
: base(databaseFactory) { }
public int HolidayEntitlement(int userId)
{
return HolidayEntitlement(userId, DateTime.Now);
}
public int HolidayEntitlement(int userId, DateTime dateTime)
{
//Get the User
var user = this.GetSingleById(userId);
//Work Total Entitlement
int entitlement = user.BaseHolidayEntitlement;
//Years in Service
entitlement += (dateTime - user.EmploymentStartDate).Days / 365;
return entitlement;
}
public int RemainingHolidayEntitlement(int userId)
{
return RemainingHolidayEntitlement(userId, DateTime.Now);
}
public int RemainingHolidayEntitlement(int userId, DateTime dateTime)
{
return int.MinValue;
}
}
我想对 HolidayEntitlement(int userId, DateTime dateTime) 进行单元测试,但我需要在方法中模拟 GetSingleById 部分
我把它写成一个测试,但它没有编译。
[TestMethod]
public void GetHolidayEntitlement25()
{
//How to write this Unit test
//Setup
var user = new User { AnnualHolidayIncrement = 1, BaseHolidayEntitlement = 25, EmploymentStartDate = new DateTime(2013, 1, 1),Id=1 };
Mock<UserRepository> mock = new Mock<UserRepository>();
mock.Setup(m => m.GetSingleById(1)).Returns(user);
Assert.AreEqual(25, mock.Object.HolidayEntitlement(1));
}
任何帮助,将不胜感激