Reputation: 243
I have written a multi thread code which will verify data in database and assert accordingly. But the assertions are not working in this environment.
Code to create threads
Runnable r = new WorkerThread(subasscociation);
new Thread(r).start();
new Thread(r).start();
The code for thread start function is
public class WorkerThread implements Runnable {
ArrayList<Association> alInsertedAssociations;
public WorkerThread(ArrayList<Association> alInsertedAssociations) {
this.alInsertedAssociations = alInsertedAssociations;
}
public void run() {
SecondLevelVerification slv = new SecondLevelVerification();
slv.verify(alInsertedAssociations,"add", false);
}
}
The function which asserts
public void verify(...)
{
//Code to check database
org.testng.Assert.assertNotEquals(label, 0);
}
But the code doesn't seem to work ie it doesnt assert correctly if the database doesn't have that entry.
Upvotes: 1
Views: 347
Reputation: 32454
Assertions work by throwing an exception, which in your case doesn't reach the handler installed by the testing framework. The latter monitors only the thread in which the test was started, whereas the exception is thrown from a different thread (created from within the test). See these questions for more details:
The accepted answers therein suggest how to solve your problem. Here is a draft version of a class that will allow to propagate exceptions occurring inside your threads to the testing framework:
class MyThread extends Thread implements Thread.UncaughtExceptionHandler {
Throwable interceptedException = null;
MyThread(Runnable r) {
super(r);
this.setUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable ex) {
interceptedException = ex;
}
public void myjoin() throws Throwable {
super.join();
if ( interceptedException != null )
throw interceptedException;
}
}
Your will have to use MyThread
instead of Thread
in your test code and call the myjoin()
method:
Runnable r = new WorkerThread(subasscociation);
final myThread1 = new MyThread(r);
final myThread2 = new MyThread(r);
myThread1.start();
myThread2.start();
...
myThread1.myjoin();
myThread2.myjoin();
Upvotes: 4