本文介绍了在xunit测试中模拟HostingEnvironment.QueueBackgroundWorkItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种使用的方法我希望对该调用之前的行为进行单元测试的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 04:36