如何为下面给出的方法为实体编写moq,
特别是对于像db.Entry(driver).Property(x => x.EffectiveDate).IsModified = true;
这样的属性?
public bool UpdateEffectiveDate(int driverId, DateTime effectiveDate, string UserId)
{
db myentity = new myentity();
Driver driver = db.Drivers.Find(driverId);
driver.EffectiveDate = effectiveDate;
driver.LastModifiedBy = UserId;
driver.LastModifiedDate = DateTime.Now;
db.Drivers.Attach(driver);
db.Entry(driver).Property(x => x.EffectiveDate).IsModified = true;
db.Entry(driver).Property(x => x.LastModifiedBy).IsModified = true;
db.Entry(driver).Property(x => x.LastModifiedDate).IsModified = true;
return (db.SaveChanges() > 0);
}
答案 0 :(得分:0)
您需要更改方法以使用方法注入。
public bool UpdateEffectiveDate(db aEntity, int driverId, DateTime effectiveDate, string UserId)
{
//db myentity = new myentity();
Driver driver = aEntity.Drivers.Find(driverId);
driver.EffectiveDate = effectiveDate;
driver.LastModifiedBy = UserId;
driver.LastModifiedDate = DateTime.Now;
aEntity.Drivers.Attach(driver);
aEntity.Entry(driver).Property(x => x.EffectiveDate).IsModified = true;
aEntity.Entry(driver).Property(x => x.LastModifiedBy).IsModified = true;
aEntity.Entry(driver).Property(x => x.LastModifiedDate).IsModified = true;
return (aEntity.SaveChanges() > 0);
}
然后你就像这样设置你的测试......
var _MockEntity = new Mock<db>();
var _MockDrivers = new Mock<Drivers>();
var _MockDriver = new Mock<Driver>();
_MockEntity.Setup(x => x.Drivers()).Returns(() => _MockDrivers.Object);
_MockDrivers.Setup(x => x.Find(123)).Returns(() => _MockDriver.Object);
_MockDriver.SetupProperty(x => x.EffectiveDate);
_MockDriver.SetupProperty(x => x.LastModifiedBy);
_MockDriver.SetupProperty(x => x.LastModifiedDate);
myClass.UpdateEffectiveDate(_MockEntity.Object, 123, samedatehere,"test");
var _Driver = _MockDriver.Object;
var _Expected = samedatehere;
var _Actual =_Driver.EffectiveDate;
Assert.Equal(_Expected, _Actual);
进行模拟所需的几乎所有内容