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

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

问题描述

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



我正在使用eclipse作业来做服务器调用。



我想知道,如何为此写一个JUnit测试用例。

解决方案

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



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


  1. 线程管理代码:启动线程和可能会等待结果

  2. 线程中运行的worker代码

  3. 当多个线程处于活动状态时可能会导致的并发问题

构建您的实现,使您的线程管理代码对于工作人员的详细信息是不可知的。然后,您可以使用Mock Workers来启用线程管理测试,例如,Mock Worker在某些方面失败,可以让您测试管理代码中的某些路径。



实现工作人员代码,使其可以孤立运行。然后,您可以使用服务器的mocks单独测试。



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


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.

I am using eclipse Jobs to do the server call.

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. Thread Management code: the code that launches the thread(s) and perhaps waits for results
  2. The "worker" code run in the thread
  3. The concurrency issues that may result when multiple threads are active

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.

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

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

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

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