Zhedar
Zhedar

Reputation: 3510

How does JUnit process Unit Tests?

I'm currently testing an interface for Java which enables to use R calls with Java. Therefore I need a connection which also encapsulates a process.
Now I need to know, how JUnit processes those Unit Tests. I'm using JUnit4 with it's @Before and @After annotations to init a new connection (internally it's a process) once per test.
With "how JUnit processes" I mean:

My concern is that those tests could cause problems which wouldn't exist, if used properly (as documented) in a real environment.

Upvotes: 2

Views: 931

Answers (4)

ptyx
ptyx

Reputation: 4164

For each test class:

  1. Call @BeforeClass and/or @ClassRule annotations.
  2. For each test (@Test):
    1. Create an instance of the class
    2. Call @Before and/or @Rule annotations
    3. Call test method
    4. Call @After and/or @Rule annotations
  3. Call @AfterClass or @ClassRule annotations.

Usually everything works from the same thread - however don't rely on that as some rules (timeout) will fork a thread - and you can decide to run tests in parallel.

Upvotes: 1

Gangnus
Gangnus

Reputation: 24464

  • is every test executed in it's own thread? ( which could probably cause problems) - one thread for all tests
  • are those tests executed sequentially? - yes
  • do they have a specific order (not that important, but would be nice to know) - no, it is principally impossible to tell beforehand the order of processing of @Test methods in the class. But using @Rules, you can read the number of the current test in their sequence

  • Of course, we are talking on different tests in one class.

Upvotes: 1

Thorn G
Thorn G

Reputation: 12766

I believe that unless otherwise specified, JUnit is free to use as many threads as it likes to run your unit tests. You can restrict this to a single thread. The order is arbitrary as to which tests are run when. In theory, your tests should be properly thread-safe to avoid having nondeterminism issues if run from different threads.

Upvotes: 1

Woot4Moo
Woot4Moo

Reputation: 24316

The tests are executed sequentially. You should not rely on this fact, because that indicates you are not writing a pure unit test and have created an anti-pattern (in terms of testing). Each test must be its own separate piece of work with no external dependencies outside of After and Before initializations. I believe each test is executed in its own thread, once again this harkens back to your test suite not being pure unit tests.

My concern is that those tests could cause problems which wouldn't exist, if used properly (as documented) in a real environment.

Unit tests only validate one small piece of a function, typically one possible logic branch. If you want to test the system integration you will need to do what is called integration testing. Further if you are looking to do multi-threaded testing I highly recommend: Multi-threaded TC

Upvotes: 2

Related Questions