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. e.g. Say CustomerTest
This CustomerTest have -
- A test with
@BeforeClass
tag - it gets the stored instance of MyObject. - Other tests will use MyObject, perform some operation and do the tests
- A test with
@AfterClass
tag - does destroy the instance of MyObject
- A test with
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.
精彩评论