我正在寻找 .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/