我有一种使用的方法 我希望对该调用之前的行为进行单元测试的HostingEnvironment.QueueBackgroundWorkItem,但是测试失败,并显示System.InvalidOperationException : Operation is not valid due to the current state of the object.
I have a method using HostingEnvironment.QueueBackgroundWorkItem which I wish to unit test some behaviour before this call, however, the test is failing with System.InvalidOperationException : Operation is not valid due to the current state of the object.
我怀疑这需要模拟HostingEnvironment,但不知道如何操作.
I suspect this I need to mock the HostingEnvironment but unaware of how to.
推荐答案为解决此问题,我定义了一个接口
To resolve this issue I defined an interface
public interface ITaskScheduler { void QueueBackgroundWorkItem(Action<CancellationToken> workItem); }在生产代码中,我注入了实现
In production code I inject implementation
public class AspNetTaskScheduler : ITaskScheduler { public void QueueBackgroundWorkItem(Action<CancellationToken> workItem) { HostingEnvironment.QueueBackgroundWorkItem(workItem); } }在测试代码中,我注入了实现
In test code I inject implementation
public class TaskScheduler : ITaskScheduler { public void QueueBackgroundWorkItem(Action<CancellationToken> workItem) { workItem.Invoke(new CancellationToken()); } }我认为这是一个不错的解决方案,因为单元测试可以正常工作,并且我的排队后台任务的类与HostingEnvironment分离.
I think this is an OK solution since unit tests work and my classes that queue background tasks are decoupled from HostingEnvironment.
更多推荐
在xunit测试中模拟HostingEnvironment.QueueBackgroundWorkItem
发布评论