In TestNG i am trying to undertand the use of singleThreaded=true
attibute of @Test
Annotation .I already referred http://testng.org/doc/documentation-main.html and
http://beust.com/weblog2/archives/000407.html but didn’t got much help .
My Question : Why do we need to execute method on single thread. Running on multiple thread can save out time.
Note : In the example given at http://beust.com/weblog2/archives/000407.html
He said :: “the two test methods testf1()
and testf2()
test the methods A#f1
and A#f2
respectively, but when you ask TestNG to run these tests in parallel mode, these two methods will be invoked from different threads, and if they don’t properly synchronize with each other, you will most likely end up in a corrupt state.
Can anyone explain with code the above example
Advertisement
Answer
I recently used this setting because the tests needed so. Example, we have entity1 & entity2 and we do some operations on those entities, only one operation at a time is allowed on the entities and conflict error is given back to user if user tried to run multiple operations. To test all the scenarios, tests have to executed one at a time. To achieve that tests have to run in singleThreaded mode.
Updated with an example Below is a madeup exampe based on real world scenario. We have devices which collect temperature and humidity. We have fixed number of devices to test in lower environment. Devices can perform only one task at a time.
class XDevice { private String id; } class WorkOrchestrator { public long createWork(Collection<String> devices, WorkTypeEnum workType) { if(areDevicesBusy(devices)) { //devices are already performing some work throw new ConflictException(); } else { if (workType == TEMPERATURE) { handleTemperature(devices); } else if (workType == HUMIDITY) { handleHumidity(devices); } } } } class TemperatureHandler { public handleTemperature(Collection<String> devices) { //handle temperature related stuff } } class HumidityHandler { public handleHumidity(Collection<String> devices) { //handle humidity related stuff } } @Test(SingeThreaded = true) class XDeviceIT { //we have fixed list of devices for testing private Collection<XDevice> devices; @Test public testAverageTemperatureCollectedFromDevices() { } @Test public testAverageHumidityCollectedFromDevices() { } }