Bird
Raised Fist0
JUnittesting~5 mins

Testing no exception thrown in JUnit

Choose your learning style10 modes available
Introduction

We check that a piece of code runs without errors to make sure it works as expected.

When you want to confirm a method completes successfully without crashing.
When testing code that should not throw any errors under normal conditions.
When verifying that input values do not cause exceptions.
When ensuring that setup or initialization code runs smoothly.
When validating that a function handles edge cases without exceptions.
Syntax
JUnit
assertDoesNotThrow(() -> {
    // code that should not throw an exception
});

This syntax uses a lambda expression to run the code.

If the code throws an exception, the test will fail.

Examples
Checks that simple math does not throw an exception.
JUnit
assertDoesNotThrow(() -> {
    int result = 5 + 3;
});
Verifies adding an item to a list does not cause errors.
JUnit
assertDoesNotThrow(() -> {
    List<String> list = new ArrayList<>();
    list.add("item");
});
Tests that handling a null value does not throw an exception.
JUnit
assertDoesNotThrow(() -> {
    String text = null;
    if (text == null) {
        text = "default";
    }
});
Sample Program

This test checks that adding items to a list does not throw any exceptions.

JUnit
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;

public class NoExceptionTest {

    @Test
    void testNoExceptionThrown() {
        assertDoesNotThrow(() -> {
            List<String> items = new ArrayList<>();
            items.add("apple");
            items.add("banana");
        });
    }
}
OutputSuccess
Important Notes

Use assertDoesNotThrow to keep tests clear and focused on error-free execution.

It helps catch unexpected exceptions early in development.

Summary

Use assertDoesNotThrow to confirm code runs without errors.

This improves confidence that your code handles inputs safely.

It is simple and keeps tests clean and readable.

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