Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit. Parallel running. But all the test methods processing singleton instance. How to solve?

So, I have a couple of JUnit classes, each one contains a list of test methods. Each method is independent of each other, there is no direct connection. But we have indirect connection: all methods processes one singleton object (it is Selenium Web Driver Instance, yes, I use 1 Web Driver Instance for all my tests, because for making new object instance we spend a really lot of time! ).

And It is all ok, when test methods execute step by step in one thread. But it is too long too,

So, I decided to increase speed, How? - I decided to run all the test methods in the parallel mode. For this I use maven with the special configuration for parallel test execution.

But I think, it is a source a new problem, because - in result we have parallel methods execution, but we still work just with single Web Driver Instance.

I'm trying to find the optimal solution:

I want that the tests will be executed in parallel mode - it is really fast.

I don't want that for every test new object is created - it is a very long process.

What advice can you provide for me?

How would you have solved this problem?

like image 390
user471011 Avatar asked Feb 17 '26 08:02

user471011


2 Answers

Unfortunately, webDriver is not thread-safe. Imho, best practice is to run each test class using individual webDriver instance in separate thread. The optimal number of threads is int threadNum = Runtime.getRuntime().availableProcessors() * 2; The executing time of my projects reduced from 30 minutes to 4. Exactly the same method is used in Thucydides framework.

like image 135
Pazonec Avatar answered Feb 19 '26 22:02

Pazonec


There is no alternative around this. If the tests are running in parallel, you can not use a single WebDriver instance, you must instantiate one WebDriver instance per test case.

One way to get a speedup by running the tests serially is to reuse the WebDriver object because starting up the WebDriver tends to be a step which takes a long time. Another common optimisation is to reuse the FirefoxProfile if a FirefoxDriver is being used because the creation of the profile is also slow.

If you do choose to reuse the WebDriver object, make sure you try to clean up the instance as best as possible in tearDown. For example, by clearing cookies:

driver.manage().deleteAllCookies();
like image 44
Mike Kwan Avatar answered Feb 19 '26 20:02

Mike Kwan