Bird
Raised Fist0
JUnittesting~8 mins

Testing no exception thrown in JUnit - Framework Patterns

Choose your learning style10 modes available
Framework Mode - Testing no exception thrown
Folder Structure
src/
└── test/
    └── java/
        └── com/
            └── example/
                ├── pages/
                │   └── LoginPage.java
                ├── tests/
                │   └── LoginTests.java
                ├── utils/
                │   └── TestUtils.java
                └── config/
                    └── TestConfig.java
Test Framework Layers
  • Driver Layer: Manages WebDriver setup and teardown for browser control.
  • Page Objects: Encapsulate UI elements and actions for each page (e.g., LoginPage).
  • Tests: Contains JUnit test classes with test methods verifying behavior.
  • Utilities: Helper methods for common tasks like waits, data generation.
  • Configuration: Holds environment settings, credentials, and browser options.
Configuration Patterns
  • Use TestConfig.java to load environment variables and test parameters.
  • Use system properties or a config file (e.g., config.properties) for browser choice and URLs.
  • Keep sensitive data like credentials outside source code, load securely at runtime.
  • Allow switching environments (dev, staging, prod) via config settings.
Test Reporting and CI/CD Integration
  • Use JUnit's built-in reports for pass/fail results.
  • Integrate with CI tools (Jenkins, GitHub Actions) to run tests on code changes.
  • Generate HTML or XML reports for easy review.
  • Fail build if any test throws unexpected exceptions.
Best Practices
  • Use assertDoesNotThrow() in JUnit 5 to verify no exceptions occur.
  • Write clear test method names describing the expected behavior.
  • Keep tests independent and repeatable without side effects.
  • Use Page Object Model to separate UI logic from tests.
  • Handle setup and cleanup in @BeforeEach and @AfterEach methods.
Self Check

Where in this folder structure would you add a new test method to verify that a user login does not throw any exceptions?

Key Result
Use JUnit's assertDoesNotThrow in well-structured tests under src/test/java with Page Objects and config management.

Practice

(1/5)
1. What is the main purpose of assertDoesNotThrow in JUnit testing?
easy
A. To assert that a method returns a specific value
B. To verify that a specific exception is thrown
C. To check that a block of code runs without throwing any exceptions
D. To test if a method runs within a time limit

Solution

  1. Step 1: Understand the purpose of assertDoesNotThrow

    This assertion is used to confirm that no exceptions occur when running a piece of code.
  2. Step 2: Compare with other assertions

    Unlike assertions that check for exceptions or return values, assertDoesNotThrow ensures smooth execution without errors.
  3. Final Answer:

    To check that a block of code runs without throwing any exceptions -> Option C
  4. Quick Check:

    assertDoesNotThrow = no exceptions thrown [OK]
Hint: Remember: assertDoesNotThrow means code runs error-free [OK]
Common Mistakes:
  • Confusing assertDoesNotThrow with assertThrows
  • Thinking it checks return values
  • Assuming it tests performance or timing
2. Which of the following is the correct syntax to test that no exception is thrown by myMethod() using JUnit 5?
easy
A. assertDoesNotThrow(() -> myMethod());
B. assertThrows(() -> myMethod());
C. assertNoException(myMethod());
D. assertDoesNotThrow(myMethod);

Solution

  1. Step 1: Recall the correct method signature

    In JUnit 5, assertDoesNotThrow takes a lambda expression or executable block, like () -> myMethod().
  2. Step 2: Identify correct syntax

    assertDoesNotThrow(() -> myMethod()); correctly uses a lambda expression. assertThrows(() -> myMethod()); tests for exceptions, non-existent methods like assertNoException(myMethod()); won't work, and assertDoesNotThrow(myMethod); misses lambda syntax.
  3. Final Answer:

    assertDoesNotThrow(() -> myMethod()); -> Option A
  4. Quick Check:

    Use lambda with assertDoesNotThrow [OK]
Hint: Use lambda syntax () -> method() inside assertDoesNotThrow [OK]
Common Mistakes:
  • Using assertThrows instead of assertDoesNotThrow
  • Passing method reference without lambda
  • Using non-existent assertion methods
3. Consider the following JUnit test code:
assertDoesNotThrow(() -> {
    int result = 10 / 2;
    System.out.println(result);
});

What will be the test result when this test runs?
medium
A. Test fails due to syntax error
B. Test fails due to ArithmeticException
C. Test fails due to NullPointerException
D. Test passes because no exception is thrown

Solution

  1. Step 1: Analyze the code inside assertDoesNotThrow

    The code divides 10 by 2, which is valid and does not cause exceptions.
  2. Step 2: Determine test outcome

    Since no exception occurs, assertDoesNotThrow passes the test.
  3. Final Answer:

    Test passes because no exception is thrown -> Option D
  4. Quick Check:

    No exception means test passes [OK]
Hint: Check if code inside lambda can throw exceptions [OK]
Common Mistakes:
  • Assuming division always throws exception
  • Confusing print statements with exceptions
  • Thinking syntax error occurs without cause
4. Identify the error in this JUnit 5 test code that aims to check no exception is thrown:
@Test
void testSafeMethod() {
    assertDoesNotThrow(mySafeMethod());
}

void mySafeMethod() {
    // safe code
}
medium
A. Method mySafeMethod is not annotated with @Test
B. Missing lambda expression; method is called immediately instead of passed
C. assertDoesNotThrow cannot be used with void methods
D. Test method must return a value

Solution

  1. Step 1: Check how assertDoesNotThrow is called

    The code calls mySafeMethod() immediately and passes its result, which is void, instead of passing a lambda.
  2. Step 2: Correct usage of assertDoesNotThrow

    It requires a lambda like () -> mySafeMethod() to defer execution and catch exceptions.
  3. Final Answer:

    Missing lambda expression; method is called immediately instead of passed -> Option B
  4. Quick Check:

    Pass lambda, not method call, to assertDoesNotThrow [OK]
Hint: Always wrap method call in lambda for assertDoesNotThrow [OK]
Common Mistakes:
  • Calling method instead of passing lambda
  • Thinking void methods can't be tested
  • Ignoring lambda syntax requirement
5. You want to test that a method processData(String input) does not throw exceptions for any non-null input. Which JUnit 5 test code correctly tests this for inputs "hello" and "world" using assertDoesNotThrow?
hard
A. assertDoesNotThrow(() -> { processData("hello"); processData("world"); });
B. assertDoesNotThrow(processData("hello")); assertDoesNotThrow(processData("world"));
C. assertDoesNotThrow(() -> processData("hello", "world"));
D. assertDoesNotThrow(() -> { processData(null); });

Solution

  1. Step 1: Understand the requirement

    We want to test that processData does not throw exceptions for both inputs "hello" and "world".
  2. Step 2: Check which code tests both inputs in one assertion

    assertDoesNotThrow(() -> { processData("hello"); processData("world"); }); runs both calls inside one lambda passed to assertDoesNotThrow, ensuring both run without exceptions.
  3. Step 3: Analyze other options

    The two separate assertDoesNotThrow(processData(...)) calls execute methods immediately without lambdas, which is incorrect. assertDoesNotThrow(() -> processData("hello", "world")); passes two arguments to a one-argument method. assertDoesNotThrow(() -> { processData(null); }); tests null input, which is not required.
  4. Final Answer:

    assertDoesNotThrow(() -> { processData("hello"); processData("world"); }); -> Option A
  5. Quick Check:

    Group calls in one lambda for multiple inputs [OK]
Hint: Put multiple calls inside one lambda for combined assertDoesNotThrow [OK]
Common Mistakes:
  • Passing wrong number of arguments
  • Testing null input when not required
  • Forgetting lambda expressions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard