简体   繁体   中英

How to create moq for property in Entity Framework

How do I write moq for an entity for the method given below, especially for properties like 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);
}

You'll need to change your Method to use Method Injection.

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);
}

Then you setup your test like so...

  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);  

Almost everything you need to learn how to mock with moq https://github.com/Moq/moq4/wiki/Quickstart

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM