Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

java - How do I write a JUnit test case to test threads and events

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...