单元测试仅在构建服务器

时间:2016-03-24 14:42:38

标签: c# unit-testing datetime nunit xunit

为了帮助进行单元测试,我们在委托中包含了DateTime类,以便在单元测试中覆盖DateTime.Now

public static class SystemTime
{
    #region Static Fields

    public static Func<DateTime> Now = () => DateTime.Now;

    #endregion
}

以下是在xunit单元测试中使用它的一个示例:

[Fact]
public void it_should_update_the_last_accessed_timestamp_on_an_entry()
{
    // Arrange
    var service = this.CreateClassUnderTest();

    var expectedTimestamp = SystemTime.Now();
    SystemTime.Now = () => expectedTimestamp;

    // Act
    service.UpdateLastAccessedTimestamp(this._testEntry); 

    // Assert
    Assert.Equal(expectedTimestamp, this._testEntry.LastAccessedOn);
}   

测试在本地运行正常,但是在我们的构建服务器上失败,因为Assert语句中的日期时间不同。

我很难想到它会失败的原因,因为DateTime是通过上面提到的委托包装器嘲笑的。我已经验证了UpdateLastAccessedTimestamp方法的实现没有问题,并且测试在本地运行时通过。

不幸的是我无法在我们的构建服务器上调试它。任何想法为什么它只会在构建服务器上运行时失败?

请注意UpdateLastAccessedTimestamp的实施如下:

public void UpdateLastAccessedTimestamp(Entry entry)
{
    entry.LastAccessedOn = SystemTime.Now();
    this._unitOfWork.Entries.Update(entry);
    this._unitOfWork.Save();
}

Entry类只是一个简单的POCO类,它包含许多字段,包括LastAccessedOn字段:

public class Entry
{
   public DateTime LastAccessedOn { get; set; }

   //other fields that have left out to keep the example concise
}

2 个答案:

答案 0 :(得分:3)

您的问题可能是由于多个单元测试与static SystemTime一起使用。例如,如果你有类似的东西:

单元测试1

[Fact]
public void it_should_update_the_last_accessed_timestamp_on_an_entry()
{
    // Arrange
    var service = this.CreateClassUnderTest();

    var expectedTimestamp = SystemTime.Now();
    SystemTime.Now = () => expectedTimestamp;

    // Act
    service.UpdateLastAccessedTimestamp(this._testEntry); 

    // Assert
    Assert.Equal(expectedTimestamp, this._testEntry.LastAccessedOn);
}   

public void UpdateLastAccessedTimestamp(Entry entry)
{
    entry.LastAccessedOn = SystemTime.Now();
    this._unitOfWork.Entries.Update(entry);
    this._unitOfWork.Save();
}

单元测试2

[Fact]
public void do_something_different
{
    SystemTime.Now = () => DateTime.Now;
}

因此,让我们假设单元测试2(它的整体)在单元测试1的行之间触发:

SystemTime.Now = () => expectedTimestamp;

// Unit test 2 starts execution here

// Act
service.UpdateLastAccessedTimestamp(this._testEntry); 

如果出现这种情况,那么您的UpdateLastAccessedTimestamp不会(必然)拥有您在DateTime设置的预期SystemTime.Now = () => expectedTimestamp;值,因为另一项测试已覆盖您的功能已从单元测试1提供。

这就是为什么我认为你最好不要将DateTime作为参数传递,或者使用注射日期时间如下:

/// <summary>
/// Injectable DateTime interface, should be used to ensure date specific logic is more testable
/// </summary>
public interface IDateTime
{
    /// <summary>
    /// Current Data time
    /// </summary>
    DateTime Now { get; }
}

/// <summary>
/// DateTime.Now - use as concrete implementation
/// </summary>
public class SystemDateTime : IDateTime
{
    /// <summary>
    /// DateTime.Now
    /// </summary>
    public DateTime Now { get { return DateTime.Now; } }
}

/// <summary>
/// DateTime - used to unit testing functionality around DateTime.Now (externalizes dependency on DateTime.Now
/// </summary>
public class MockSystemDateTime : IDateTime
{
    private readonly DateTime MockedDateTime;

    /// <summary>
    /// Take in mocked DateTime for use in testing
    /// </summary>
    /// <param name="mockedDateTime"></param>
    public MockSystemDateTime(DateTime mockedDateTime)
    {
        this.MockedDateTime = mockedDateTime;
    }

    /// <summary>
    /// DateTime passed from constructor
    /// </summary>
    public DateTime Now { get { return MockedDateTime; } }
}

使用此方案,您的服务类可能会改变(例如):

public class Service
{
    public Service() { }

    public void UpdateLastAccessedTimestamp(Entry entry)
    {
        entry.LastAccessedOn = SystemTime.Now();
        this._unitOfWork.Entries.Update(entry);
        this._unitOfWork.Save();
    }
}

对此:

    public class Service
    {

        private readonly IDateTime _iDateTime;

        public Service(IDateTime iDateTime)
        {
            if (iDateTime == null)
                throw new ArgumentNullException(nameof(iDateTime));
            // or you could new up the concrete implementation of SystemDateTime if not provided

            _iDateTime = iDateTime;
        }

        public void UpdateLastAccessedTimestamp(Entry entry)
        {
            entry.LastAccessedOn = _iDateTime.Now;
            this._unitOfWork.Entries.Update(entry);
            this._unitOfWork.Save();
        }           
    }

对于Service的实际实施,你可能会像(或使用IOC容器)那样新的:

Service service = new Service(new SystemDateTime());

对于测试,您可以使用模拟框架,也可以使用Mock类:

Service service = new Service(new MockDateTime(new DateTime(2000, 1, 1)));

您的单元测试可能会变成:

[Fact]
public void it_should_update_the_last_accessed_timestamp_on_an_entry()
{
    // Arrange
    MockDateTime mockDateTime = new MockDateTime(new DateTime 2000, 1, 1);
    var service = this.CreateClassUnderTest(mockDateTime);

    // Act
    service.UpdateLastAccessedTimestamp(this._testEntry); 

    // Assert
    Assert.Equal(mockDateTime.Now, this._testEntry.LastAccessedOn);
}   

答案 1 :(得分:0)

你很幸运,它在当地工作。要使其正常工作,您必须存储服务获取其上次访问数据时间的位置,并检查返回的时间。此时,本地计算机的速度足够快,可以在DataTime.Now上同时返回2次,而构建服务器则没有。