Und*_*ade 11 c# microsoft-fakes .net-core
我正在寻找Microsoft Fakes in .NET Core的替代方案.我知道.NET Core不再支持它.我只是不明白为什么不,我认为这在某些情况下是一个很好的解决方案.
我的问题是我想模拟DateTime.Now.以前您可以使用以下代码执行此操作:
System.Fakes.ShimDateTime.NowGet = () =>
{
return new DateTime(2000, 1, 1);
};
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅Microsoft文档中的链接:https://docs.microsoft.com/en-us/visualstudio/test/using-shims-to-isolate-your-application-from-other-assemblies -用于单元测试?视图= 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我将此解决方案归功于下一个StackOverflow帖子: 单元测试:DateTime.Now
但是我对这个解决方案还不满意,因为我觉得我必须调整我的测试实现.我不认为这是可取的.
我希望有人可以帮助我,谢谢你的努力.
姿势对此很好。
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);
Run Code Online (Sandbox Code Playgroud)
我正在寻找 .NET Core 中 Microsoft Fakes 的替代品。我知道 .NET Core 不再支持它。我只是不明白为什么不,我认为在某些情况下这是一个很好的解决方案。
自 2020 年 5 月 19 日起,Microsoft Fakes 支持 .NET Core。
https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes#16.6.0
| 归档时间: |
|
| 查看次数: |
3120 次 |
| 最近记录: |