如何对生成线程的方法进行单元测试?

发布于 2024-08-18 11:07:41 字数 430 浏览 4 评论 0原文

我对 TDD 相当陌生,但已经使用它足够长的时间来了解如何使用模拟、存根、依赖注入、控制反转来解决“类似”问题......但出于某种原因,我对使用依赖注入感到非常不安并传入“IThread”(或类似的)。

为了给它一些基本的上下文 - 我正在尝试向遗留应用程序添加单元测试,但我不确定如何对构造函数生成两个线程的类进行单元测试。

使用依赖注入是唯一的选择吗?

如果是的话,线程带来的功能怎么样?按照目前的情况,线程都运行 while(true) 循环并且永远不会退出循环(除非应用程序终止)。循环内部有合理的代码块,我真正想要测试的正是这段代码。

更糟糕的是,我不想将所有功能从循环中取出并放入 public 方法中(我只是测试公共方法,因为我的测试存在于另一个项目中),因为它真的会减少代码中其他地方的类的易用性。

有什么建议吗?

I am fairly new to TDD but have been using it for long enough to understand how to use mocks, stubs, dependency injection, inversion of control to solve 'similar' problems... but for some reason I feel very uneasy about using dependency injection and passing in an 'IThread' (or similar).

To give it some basic context - I am trying to add unit tests to a legacy application and I am unsure of how to unit test a class who's constructor spawns two threads.

Is the only option to use dependency injection?

If so what about the functionality that the threads bring? As it stands the threads both run while(true) loops and never exit the loop (unless the application is terminating). Inside the loops there are reasonable chunks of code and it's this code that I really want to have under test.

To make matters worse I don't want to pull all the functionality out of the loops and into public methods (I'm only testing public methods as my tests exist in another project) as it will really decrease the easy of use of the class elsewhere in the code.

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨夜星沙 2024-08-25 11:07:41

您能否将功能引入内部方法并使用InternalsVisibleTo 而是?即使您确实希望它们保密,这也是一个合理的折衷解决方案。

如果你的线程通常会永远运行,这确实会让测试变得非常困难......而且听起来你真的应该单独测试“线程做什么”部分,如果它们不依赖 关于处于单独的线程中。

偶尔有用的一个选项是拥有一个 IScheduler 类型的接口 - 要求它在任何它认为合适的地方执行一个操作;生产线程将创建一个新线程,但您的测试线程可以在现有线程中(或在您在测试代码中控制的线程上)运行该操作。我不确定这是否适合您这里的情况,线程将永远运行,但您可能需要在其他情况下考虑它。

Could you pull the functionality into internal methods and use InternalsVisibleTo instead? Even if you'd really want them to be private, this is a reasonable compromise solution.

If your threads would normally run forever, that does make it very hard to test... and it sounds like you really should be testing the "what the threads do" part separately, if they don't depend on being in separate threads.

One option which is occasionally useful is to have an IScheduler type of interface - ask that to execute an action wherever it sees fit; the production one would create a new thread, but your test one could run the action within the existing thread (or on a thread you had control over within your test code). I'm not sure that's appropriate for your situation here, where the thread would run forever, but you might want to think about it in other situatoins.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文