Challenge - 5 Problems
JUnit Unit Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
JUnit test method output
What will be the result of running this JUnit 5 test method?
JUnit
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class CalculatorTest { @Test void testAdd() { int result = 2 + 3; assertEquals(5, result); } }
Attempts:
2 left
π‘ Hint
Check the assertion and the calculation result.
β Incorrect
The test adds 2 and 3, expecting 5. The assertion matches the result, so the test passes.
β assertion
intermediate2:00remaining
Correct assertion for exception testing
Which JUnit 5 assertion correctly tests that a method throws a NullPointerException?
JUnit
void methodThatThrows() {
throw new NullPointerException();
}Attempts:
2 left
π‘ Hint
Look for the assertion designed to check exceptions.
β Incorrect
assertThrows expects the exception class and a lambda that runs the method. It passes if the exception is thrown.
π§ Debug
advanced2:00remaining
Identify the cause of test failure
Given this JUnit 5 test, why does it fail?
JUnit
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class StringTest { @Test void testLength() { String s = null; assertEquals(4, s.length()); } }
Attempts:
2 left
π‘ Hint
Think about calling a method on a null object.
β Incorrect
Calling length() on a null String causes NullPointerException at runtime, failing the test.
π§ Conceptual
advanced1:30remaining
Purpose of unit testing
What is the main purpose of unit testing in software development?
Attempts:
2 left
π‘ Hint
Unit testing focuses on small pieces of code, not the whole system.
β Incorrect
Unit testing checks small code units like methods or classes to ensure they behave as expected.
β framework
expert2:30remaining
JUnit 5 lifecycle method order
What is the correct order of JUnit 5 lifecycle methods when running multiple tests in a class?
Attempts:
2 left
π‘ Hint
Remember which methods run once per class and which run before/after each test.
β Incorrect
@BeforeAll runs once before all tests, @BeforeEach before each test, then @Test, @AfterEach after each test, and @AfterAll once after all tests.