0

I have created two classes which extends Thread and implements the run method.

class A extends Thread implements MyInterface { public void run() { } public function() { B b= new b(); b.start(); } } class B extends Thread implements OtherInterafce { MyClassC object = new MyClassC(); public void run() { for(;;) { object.callMethod(); object.callMethod2(); //Perform some operations } } } 

Now I want to write unit Test for these classes, Since Class B is creating a daemon thread there is no exit condition, I am not sure how to test this part. I can create a mock of object but how many times that will run I am not sure, so how should I very the calls to the methods.

1
  • Class B does not create a thread. Class B is a Thread instance, and its run() method will be run in a thread if some other thread calls new B().start(). Commented Feb 12, 2015 at 13:57

2 Answers 2

3

Unit testing multithreading is very hard. Better just test the logic and not the threading. You could extract the inner part and test it in isolation:

public void run() { for(;;) { performOperations(object); } } public performOperations(MyClassC object) { object.callMethod(); object.callMethod2(); //Perform some operations } 

Then you can create a test for performOperations().

Sign up to request clarification or add additional context in comments.

Comments

1

You need some way to terminate your thread. There are many ways to do this, so I suggest you research the topic. One example is a volatile flag, which is examined every time your thread loops.

Once you can terminate the thread, then you can test it. There are a few options on how to do this. The easiest might be to create a thread that always executes once, then checks for a cancellation flag. I.e. a structure like:

public void run() { do { object.callMethod(); object.callMethod2(); //Perform some operations } while (conditionIsTrue); } 

In your test you can construct your thread object and immediately set the flag to false. Then your thread will run just once around the loop, allowing you to accurately verify interactions with your mocked object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.