c# - .NET Core 中 Microsoft Fakes 的任何替代方案?

标签 c# .net-core microsoft-fakes

我正在寻找 .NET Core 中 Microsoft Fakes 的替代品。我知道 .NET Core 不再支持它。我只是不明白为什么不,我认为在某些情况下这是一个很好的解决方案。

我的问题是我想模拟 DateTime.Now。以前您可以使用以下代码执行此操作:

System.Fakes.ShimDateTime.NowGet = () => 
{ 
   return new DateTime(2000, 1, 1); 
};

它在 Microsoft 文档中有描述,请参阅链接以获取更多信息:https://learn.microsoft.com/en-us/visualstudio/test/using-shims-to-isolate-your-application-from-other-assemblies-for-unit-testing?view=vs-2017

现在我通过为 DateTime 创建一个包装器来解决它,它看起来像这样:

/// <summary>
/// Used for getting DateTime.Now(), time is changeable for unit testing
/// </summary>
public static class SystemTime
{
   /// <summary> 
   /// Normally this is a pass-through to DateTime.Now, but it can be 
   /// overridden with SetDateTime( .. ) for testing or debugging.
   /// </summary>
   public static Func<DateTime> Now = () => DateTime.Now;

   /// <summary> 
   /// Set time to return when SystemTime.Now() is called.
   /// </summary>
   public static void SetDateTime(DateTime dateTimeNow)
   {
      Now = () =>  dateTimeNow;
   }

   /// <summary> 
   /// Resets SystemTime.Now() to return DateTime.Now.
   /// </summary>
   public static void ResetDateTime()
   {
       Now = () => DateTime.Now;
   }
}

这个解决方案归功于下一篇 StackOverflow 帖子: Unit Testing: DateTime.Now

但我对这个解决方案还不满意,因为我觉得我必须为我的测试调整我的实现。我认为这是不可取的。

我希望有人能帮我解决这个问题,在此先感谢您的努力。

最佳答案

Pose为此效果很好。

using Pose;

Shim dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 4, 4));

// This block executes immediately
PoseContext.Isolate(() =>
{
    // All code that executes within this block
    // is isolated and shimmed methods are replaced

    // Outputs "4/4/04 12:00:00 AM"
    Console.WriteLine(DateTime.Now);

}, dateTimeShim);

关于c# - .NET Core 中 Microsoft Fakes 的任何替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52497439/

相关文章:

javascript - 如何从 Azure Active Directory 获取 API 和 Microsoft Graph 的有效访问 token ?

c# - 休息 API : Passing Colon (:) in url using attribute Routing doesn't work

c# - 我是否在我的测试方法中 stub 或填充方法?

visual-studio-2015 - MS 假货/垫片与 VS2015 专业版?

c# - 如何使用 FK 设置集合属性?

c# - 如何替换前导空格但保留多行?

sockets - RST上的TCP重传-Windows和Linux上的套接字行为不同?

c# - MS Visual Studio 2012 中的 Shim NotSupportedException

c# - 通过以字符串开头的属性在xml中查找节点

c# - 使用 XNA 游戏以试用模式进入 Marketplace