Tests & Thread Safety - dn0000001/test-automation GitHub Wiki

For the most part, it is not necessary to consider thread safety in tests (provided you are using non-static variables.) However, there is 1 specify case that requires special consideration. This is when your test uses a data provider.

Why Thread Safety needs to be considered when using a Data Provider

We are using the TestNG data provider feature and we need to understand how it works. First TestNG will launch a single thread for the data provider method, this will launch multiple threads as needed for the test method. Once all the tests complete, the after test methods will execute. So, due to the possibility of multiple threads running at the same time we need to ensure the code is thread safe.

What actions are not thread safe

There are many actions that may not be thread safe. However, for automation there tends to mainly 1 type of action. This action is the collection of information that is stored in a global variable in the scope of the test. For example, putting objects in a list in the test method that gets processed after the test.

How to make the collection of information thread safe

For lists, consider using a queue instead which has a thread safe implementation of ConcurrentLinkedQueue. For maps, use the thread safe implementation ConcurrentHashMap or SynchronizedHashMap.