Skip to content

Ensure @Before and @Test run on the same thread in AndroidJUnit4ClassRunner.#2479

Open
copybara-service[bot] wants to merge 1 commit intomainfrom
piper_895547043
Open

Ensure @Before and @Test run on the same thread in AndroidJUnit4ClassRunner.#2479
copybara-service[bot] wants to merge 1 commit intomainfrom
piper_895547043

Conversation

@copybara-service
Copy link
Copy Markdown

Ensure @before and @test run on the same thread in AndroidJUnit4ClassRunner.

Currently, AndroidJUnit4ClassRunner inherits standard JUnit 4 behavior where
timeouts are applied only to the test method itself. If a test timeout is
set (e.g., passed by TradeFed or runner arguments), FailOnTimeout executes
the test method in a separate thread.

Since setup (@before) and teardown (@after) are applied outside this
timeout, they run on the caller thread, causing a thread mismatch. This
prevents ThreadLocal variables initialized in setup from being accessible in
the test.

This CL modifies AndroidJUnit4ClassRunner to apply the timeout to the
combined statement of setup, test, and teardown. This is achieved by:

  1. Overriding withAfters to wrap the combined statement in FailOnTimeout.
  2. Overriding withPotentialTimeout to be a no-op, preventing double
    timeout application.

This ensures all lifecycle methods run on the same thread spawned by the
timeout.

NOTE: Because the timeout now wraps setup and teardown, any time spent in
@before or @after will now count towards the test timeout.

…Runner.

Currently, AndroidJUnit4ClassRunner inherits standard JUnit 4 behavior where
timeouts are applied only to the test method itself. If a test timeout is
set (e.g., passed by TradeFed or runner arguments), FailOnTimeout executes
the test method in a separate thread.

Since setup (@before) and teardown (@after) are applied outside this
timeout, they run on the caller thread, causing a thread mismatch. This
prevents ThreadLocal variables initialized in setup from being accessible in
the test.

This CL modifies AndroidJUnit4ClassRunner to apply the timeout to the
combined statement of setup, test, and teardown. This is achieved by:
  1. Overriding withAfters to wrap the combined statement in FailOnTimeout.
  2. Overriding withPotentialTimeout to be a no-op, preventing double
     timeout application.

This ensures all lifecycle methods run on the same thread spawned by the
timeout.

NOTE: Because the timeout now wraps setup and teardown, any time spent in
@before or @after will now count towards the test timeout.

PiperOrigin-RevId: 895547043
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant