Addiction006
Addiction006

Reputation: 31

How to unit test a property changed event

I have a service that allows me to handle a property event (it will fire when StartDateTime changes) and I would like to know how to unit test this service, or how to begin unit test this property change. Do I have to mock this service?

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

    }
}

Edit: this is what I've tried, but I still don't know how to test if the StartDateTime is call

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

    }

}

Upvotes: 0

Views: 3658

Answers (1)

Addiction006
Addiction006

Reputation: 31

I had help and found the solution. what I needed was mock the interface inside my constructor, then I can set up that mock

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

Upvotes: 2

Related Questions