问题描述
我有一个方法使用HostingEnvironment.QueueBackgroundWorkItem
我希望在此调用之前对某些行为进行单元测试,但是,测试失败并显示 System.InvalidOperationException :由于对象的当前状态,操作无效.代码>
I have a method usingHostingEnvironment.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!