Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent JUnit testing

I have a large JUnit test suite, where I'd quite like to run all the tests concurrently for two reasons:

  • Exploit multiple cores to run the whole test suite faster
  • Hopefully detect some errors due to non-thread-safe global objects

I recognise that this will force me to refactor some code to make it thread-safe, but I consider that to be a good thing :-)

What's the best way to get JUnit to run all the tests concurrently?

like image 641
mikera Avatar asked Feb 11 '11 15:02

mikera


People also ask

Do JUnit tests run concurrently?

Once parallel test execution property is enabled, the JUnit Jupiter engine will execute tests in parallel according to the provided configuration with declared synchronization mechanisms.

Can we do parallel testing in JUnit?

Yes, You can. Show activity on this post. JUnit Toolbox provides JUnit runners for parallel execution of tests.

How do I test a concurrent code?

One good way to test this is to make sure you have access to a multi-cpu machine, then run your test for as long a time/with as many iterations as possible. For example if you have a multithreaded producer consumer algorithm, fill the queue with a good sized list and use 2x as many threads as you might in production.


2 Answers

Are you fixed to JUnit? TestNG provides good multi thread testing out of the box and it's compatible with JUnit tests (you need to make a few changes). For example you could run a test like this:

@Test(threadPoolSize = 3, invocationCount = 9,  timeOut = 10000) public void doSomething() { ... } 

This would mean that the doSomething() method will be invoked 9 times by 3 different threads.

I highly recommend TestNG.

like image 186
Chandradeep Avatar answered Sep 28 '22 10:09

Chandradeep


I was looking for an answer to exactly this question, and based on the answers here, and what I read elsewhere, it appears as if there isn't currently an easy out-of-the-box way to run existing tests in parallel using JUnit. Or if there is I didn't find it. So I wrote a simple JUnit Runner that accomplishes that. Please feel free to use it; see http://falutin.net/2012/12/30/multithreaded-testing-with-junit/ for a complete explanation and the source code of the MultiThreadedRunner class. With this class, you can just annotate your existing test class(es) like this:

@RunWith(MultiThreadedRunner.class) 
like image 45
Mike Sokolov Avatar answered Sep 28 '22 10:09

Mike Sokolov