问题
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?
回答1:
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.
回答2:
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();
回答3:
Depending on where the actual performance bottlenecks are in your tests, you could do something gross like tacking a synchronized
wrapper around your driver so that you still only have one but all access to it is serialized.
You could potentially change your test to have a ThreadLocal
reference to a driver so you have one driver per thread.
回答4:
Jute maven plugin provides isolation of JUnit test methods(!) through their start as external JVM processes, also you can define specific JRE for tests
来源:https://stackoverflow.com/questions/14057314/junit-parallel-running-but-all-the-test-methods-processing-singleton-instance