简体   繁体   中英

TestNG parallel tests failing

First let me put out the structure of my tests:

  • There is BaseTest (Singleton) containing a setUp() method which runs @BeforeSuite . This setUp() method initializes MyObject which is declared as:

protected static ThreadLocal<MyObject> myObject= new ThreadLocal<MyObject>();

  • All other tests extend this BaseTest . eg Say CustomerTest

    This CustomerTest have -

    1. A test with @BeforeClass tag - it gets the stored instance of MyObject.
    2. Other tests will use MyObject, perform some operation and do the tests
    3. A test with @AfterClass tag - does destroy the instance of MyObject

So ideally, this setUp() method should run before any other test. And it runs only once .

I am trying to run test cases parallely in TestNG framework. To achieve that, I have set the parallel attribute on the suite tag of testng.xml as

<suite name="Suite" parallel="classes" thread-count="5">

Now, within the seconds after I fire the build, the build gets failed with all basic tests failed and others as skipped.

Failed test are due to java.lang.NullPointerException

My understanding is, while setUp() method is being run on a thread, some other tests on different threads are trying to access the MyObject which isn't initialized yet. So is the failure. Is my understanding correct?

If yes, what could be the possible solution to this?

Can I do something like - let the thread run first in which setUp() is being run and till then don't let other threads invoke. And once the call to setUp() finishes/ returns, then allow other threads to invoke.

( Note: My project uses Maven)

Two things:

  • NullPointerExceptions are pretty easy to track down, what does that one tell you? You should include the stack trace and the code.

  • @BeforeSuite will only be run once, but based on what you're saying, you expect it to run before each test method, which means you should use @BeforeMethod.

I have encountered this problem before. The only way I was able to overcome the issue was to remove the BeforeSuite tag on the setup method. Then each classes BeforeClass would ask if it is initialized, and if so, keep going, otherwise, it would call setup. Of course you would also have to synchronize all of these methods to the same object. That is the only way I have found to solve this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM