我有一个允许我处理属性事件的服务(它将在StartDateTime
更改时触发)并且我想知道如何对此服务进行单元测试,或者如何开始对此属性更改进行单元测试。我必须嘲笑这项服务吗?
[Export(typeof(IDriveTimeService))]
public class DriveTimeService : IDriveTimeService
{
public void Initialize(IHasDriveTimes target)
{
var _driveTimeService = new DriveTimeService ();
new DriveTimesManager(target);
}
}
DriveTimesManager
public DriveTimesManager(IHasDriveTimes target)
{
if (target != null)
{
target.PropertyChanged += HandleDriveTimesChanged;
}
}
private void HandleDriveTimesChanged(object sender, PropertyChangedEventArgs e)
{
var driveTimes = sender as IHasDriveTimes;
if (driveTimes != null)
{
if (e.PropertyName == driveTimes.GetPropertyName(t => t.StartDateTime))
{
driveTimes.StopDateTime += driveTimes.StartDateTime - _previousStartDateTime;
_previousStartDateTime = driveTimes.StartDateTime;
}
}
}
编辑:这是我尝试过的,但我仍然不知道如何测试StartDateTime是否被调用
[TestClass]
public class DriveTimeServiceTest
{
[TestMethod]
public void DriveTimeServiceNullTest()
{
var driveTimeService = new DriveTimeService();
driveTimeService.Initialize(null);
Assert.IsNotNull(driveTimeService);
}
[TestMethod]
public void DriveTimeManagerTest()
{
var propertyName = "";
var mock = new Mock<IHasDriveTimes>();
DriveTimesManager manager = new DriveTimesManager(mock.Object);
var change = new PropertyChangedEventArgs(propertyName);
mock.Verify(m => m.StartDateTime);
mock.Verify(m => m.StopDateTime);
manager.HandleDriveTimesChanged(manager, change);
}
}
答案 0 :(得分:1)
我得到了帮助并找到了解决方案。我需要的是模拟我的构造函数中的接口,然后我可以设置模拟
var driveTimeService = new DriveTimeService();
var mock = new Mock<IHasDriveTimes>().SetupAllProperties();
mock.Object.StartDateTime = DateTimeOffset.Now.Date;
mock.Object.StopDateTime = mock.Object.StartDateTime + TimeSpan.FromHours(2);
driveTimeService.Initialize(mock.Object);
mock.Object.StartDateTime += TimeSpan.FromHours(1);
mock.Raise(t => t.PropertyChanged += It.IsAny<PropertyChangedEventHandler>(), new PropertyChangedEventArgs(mock.Object.GetPropertyName(t => t.StartDateTime)));
Assert.AreEqual(mock.Object.StartDateTime + TimeSpan.FromHours(2), mock.Object.StopDateTime);