How to implemet singleThreaded=true in TestNG

2019-06-10 06:23发布

问题:

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

回答1:

As is explained here http://beust.com/weblog2/archives/000407.html ...if the classes you are testing are not multithread-safe...

So your tests can run in parallel, but if you are testing classes which are not thread safe things can break.

In example one test calls a.f1() and second one calls a.f2(). If these methods uses some shared resources in object this.a = new A() and depends on each other you will most likely end up in a corrupt state with object this.a.