如何编写 JUnit 测试用例来测试线程和事件 [英] How do I write a JUnit test case to test threads and events

查看:33
本文介绍了如何编写 JUnit 测试用例来测试线程和事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在一个(主)线程中工作的 java 代码.在主线程中,我生成了一个新线程,在其中进行服务器调用.服务器调用完成后,我在新线程中做一些工作,然后代码加入主线程.

I have a java code which works in one (main) thread. From the main thread, i spawn a new thread in which I make a server call. After the server call is done, I am doing some work in the new thread and after that the code joins the main thread.

我正在使用 eclipse Jobs 进行服务器调用.

I am using eclipse Jobs to do the server call.

我想知道,我如何为此编写 JUnit 测试用例.

I want to know, how do I write a JUnit test case for this.

推荐答案

您可能需要重构代码,以便轻松测试.

You may need to restructure your code so that it can be easily tested.

我可以看到几个不同的测试区域:

I can see several distinct areas for testing:

  1. 线程管理代码:启动线程并可能等待结果的代码
  2. 在线程中运行的worker"代码
  3. 多个线程处于活动状态时可能导致的并发问题

构建您的实现,以便您的线程管理代码与 Worker 的细节无关.然后您可以使用 Mock Worker 来启用线程管理的测试 - 例如,以某些方式失败的 Mock Worker 允许您测试管理代码中的某些路径.

Structure your implementation so that Your Thread Management code is agnostic as to the details of the Worker. Then you can use Mock Workers to enable testing of Thread Management - for example a Mock Worker that fails in certain ways allows you to test certain paths in the management code.

实现 Worker 代码,使其可以独立运行.然后,您可以使用服务器模拟来独立对其进行单元测试.

Implement the Worker code so that it can be run in isolation. You can then unit test this independently, using mocks for the server.

对于并发测试,Abhijeet Kashnia 提供的链接会有所帮助.

For concurrency testing the links provided by Abhijeet Kashnia will help.

这篇关于如何编写 JUnit 测试用例来测试线程和事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆