← Back to libraryQuestion 275 of 468
🔬TestNG & JUnitAdvanced

Test Dependencies (dependsOnMethods)

📌 Definition:

TestNG lets a test depend on another with @Test(dependsOnMethods=...) or dependsOnGroups — the dependent test runs only if its dependency PASSED, otherwise it's SKIPPED (not failed). JUnit intentionally does not support test dependencies.

📖 Detailed Explanation:

dependsOnMethods = {"login"} ensures the login test runs first and, if it fails, dependent tests are marked SKIPPED rather than failing with noise — useful for genuine ordering (can't test dashboard if login is broken). alwaysRun=true forces a config/test to run even if a dependency failed. However, over-using dependencies creates fragile chains and hides independent failures. JUnit 5 omits this feature by design, favoring independent tests; if ordering is truly needed there you use @Order. Interviewers often contrast this: TestNG supports dependencies; JUnit does not, reflecting different philosophies.

🔑 Key Points:
  • @Test(dependsOnMethods=...) — dependent runs only if dependency passed
  • Failed dependency → dependent SKIPPED (not failed)
  • alwaysRun=true forces execution despite failed deps
  • JUnit deliberately has NO test dependencies (prefers independence)
🌍 Real-World Example:

Login → dashboard → logout as a dependency chain: if login fails, dashboard/logout are SKIPPED with a clear reason, avoiding a cascade of confusing failures that all stem from the broken login.

🎯 Scenario-Based Interview Question:

In TestNG, if a @Test depends on another that FAILS, what happens to the dependent test, and does JUnit 5 offer the same feature?