stuXnet
stuXnet

Reputation: 4349

How to fail a TestNG test immediately from another thread?

I want to monitor external log files in separate threads in my Java testing framework: if a specified pattern is found in one of those monitored log files, my test (running in the main thread) should fail immediately.

I tried to interrupt the thread my test runs in, but then I would have to check after each test step for Thread.isInterrupted()

Is there a proper way to do this?

Upvotes: 0

Views: 814

Answers (1)

gustafc
gustafc

Reputation: 28865

Basically, you can't remotely fail a test the way you want. Your idea about interrupting the threads is pretty much the right thing to do, except I'd avoid interruption and instead post an event to, say, a LinkedBlockingQueue which you poll at the end of the test to see if it is empty or not.

If you want to avoid doing this in every test method, you can add the check in a method annotated with @AfterMethod.

Something like this:

public class YourTest {

 private LinkedBlockingQueue<String> errors;

 @BeforeMethod
 public void setUp() {
   errors = new LinkedBlockingQueue<>();
 }

 private void checkLogsForErrors(){
   // This is the method run in a separate thread.
   for (String line: iterateOverLogEntries()) {
     if (isError(line)) errors.add(line);
   }
 }

 @AfterMethod
 public void tearDown() {
   try {
     String error = errors.poll(100, TimeUnit.MILLISECONDS);
     fail("Found error: " + error);
   } catch (InterruptedException e){
     // No errors, great!
   }
 }

}

Edit: Oh, right, immediately. Why not run the test code itself in a separate thread and have the original thread just waiting for either an error signal from the log watcher, or a success signal from the test?

Upvotes: 3

Related Questions