我正在尝试测试 rx.net 代码,但我完全不知道该怎么做。这个网站上的一个例子很有帮助,但我无法连接最后一块。下面是一个示例代码:
class SomeClass
{
constructor(IScheduler scheduler)
{
var interval = Observable.Interval(TimeSpan.FromSeconds(1), scheduler)
.Take(5);
}
}
// So in my unit test project I'll inject a TestScheduler as below
public void Test_Some_Class()
{
var scheduler = new TestScheduler();
var instance = new SomeClass(scheduler);
...
}
我的问题是在我的启动文件中,我应该使用哪个 IScheduler 实现:
services.AddSingleton<IScheduler, ConcreteImpl>()
这个堆栈溢出问题很有帮助,但我仍然无法将所有内容拼凑在一起:(
你会使用 AsyncConversions。 像这样的东西,
services.AddSingleton<IScheduler, SchedulerDefaults.AsyncConversions>()
出于某种有趣的原因,我昨天遇到了运行时错误,但现在一切正常。 嗯!您可以使用:services.AddSingleton<IScheduler>(DefaultScheduler.Instance);
TimeBasedOperations
或按照此处的示例进行操作
public interface ISchedulerDefaults
{
IScheduler AsyncConversions { get; }
IScheduler ConstantTimeOperations { get; }
IScheduler Iteration { get; }
IScheduler TailRecursion { get; }
IScheduler TimeBasedOperations { get; }
}
并引用它,而不是services.AddSingleton<ISchedulerDefaults, SchedulerDefaults>();
对于单元测试,您可以使用:
public sealed class TestSchedulerDefaults : ISchedulerDefaults
{
private readonly TestScheduler _timeBasedOperations = new TestScheduler();
private readonly TestScheduler _asyncConversions = new TestScheduler();
private readonly TestScheduler _constantTimeOperations = new TestScheduler();
private readonly TestScheduler _iteration = new TestScheduler();
private readonly TestScheduler _tailRecursion = new TestScheduler();
IScheduler ISchedulerDefaults.AsyncConversions => new TestScheduler();
IScheduler ISchedulerDefaults.ConstantTimeOperations => new TestScheduler();
IScheduler ISchedulerDefaults.Iteration => new TestScheduler();
IScheduler ISchedulerDefaults.TailRecursion => new TestScheduler();
IScheduler ISchedulerDefaults.TimeBasedOperations => _timeBasedOperations;
public IScheduler AsyncConversions => _asyncConversions;
public IScheduler ConstantTimeOperations => _constantTimeOperations;
public IScheduler Iteration => _iteration;
public IScheduler TailRecursion => _tailRecursion;
public TestScheduler TimeBasedOperations => _timeBasedOperations;
}