Good Morning everyone.
I'm new to all the Mocking stuff and I want to test a method that calls SystemClock.Instance.GetCurrentInstant() to retrieve it as a LocalDateTime. I have a second method to cast it to string. This are both methods:
/// <summary>
/// Transforms the current instant in the user's data time zone to string following the GeneralIso format.
/// </summary>
/// <returns>
/// A string with the current instant in the user's data time zone
/// </returns>
public static string GetCurrentLocalTimeInGeneralIsoFormat()
{
return LocalDateTimePattern.GeneralIso.Format(GetCurrentLocalTime());
}
/// <summary>
/// Retrieves the current instant in the user's data time zone.
/// </summary>
/// <returns>
/// A LocalDataTime with the current instant in the user's data time zone
/// </returns>
public static LocalDateTime GetCurrentLocalTime()
{
return SystemClock.Instance.GetCurrentInstant().InZone(DateTimeZoneProviders.Bcl.GetSystemDefault()).LocalDateTime;
}
I tried the following TestMethod using a Mock:
[TestMethod]
public void TestGetCurrentLocalTimeInGeneralIsoFormat()
{
// Arrange
string expectedAnswer = "2020-02-03 12:32";
Mock<DateUtils> localTimeMock = new Mock<DateUtils>();
localTimeMock.Setup(x => DateUtils.GetCurrentLocalTimeInGeneralIsoFormat()).Returns(expectedAnswer).Verifiable();
// Act
string currentLocalDateTime = DateUtils.GetCurrentLocalTimeInGeneralIsoFormat();
// Assert
Assert.IsInstanceOfType(currentLocalDateTime, typeof(string));
Assert.AreEqual(currentLocalDateTime, expectedAnswer);
}
But I just recieve the following error:
Message:
Test method TachoShareAgent.Tests.DateUtilsTests.TestGetCurrentLocalTimeInGeneralIsoFormat threw exception:
System.NotSupportedException: Invalid setup on a static member: x => DateUtils.GetCurrentLocalTimeInGeneralIsoFormat()
I tried several approaches as implementing an interface and not using a static method, but again i'm new to all this kind of stuff and I'm a bit lost.
Thanks in advance.
Edit:
I'm aware of this solution (Mock static property with moq) but I would like to know if there are any other options apart of making a virtual element.