在xunit测试中模拟HostingEnvironment.QueueBackgroundWorkItem

编程入门 行业动态 更新时间:2024-10-28 17:22:35
本文介绍了在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

本文发布于:2023-11-14 02:07:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试中   xunit   QueueBackgroundWorkItem   HostingEnvironment

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!