Challenge - 5 Problems
JUnit @Test Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple JUnit test with @Test
What will be the result of running this JUnit test class?
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class SampleTest { @Test void testSum() { assertEquals(5, 2 + 3); } }
Attempts:
2 left
💡 Hint
Remember that @Test marks a method as a test and assertEquals checks expected vs actual values.
✗ Incorrect
The testSum method checks if 2 + 3 equals 5. Since it does, the assertion passes and the test passes without errors.
❓ assertion
intermediate2:00remaining
Identify the failing assertion in a JUnit test
Given this test method, which assertion will cause the test to fail?
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class AssertionTest { @Test void testValues() { assertTrue(3 > 2); assertFalse(5 < 1); assertEquals("hello", "hello"); assertNotNull(null); } }
Attempts:
2 left
💡 Hint
Check which assertion conditions are false or invalid.
✗ Incorrect
assertNotNull(null) fails because the argument is null, so the assertion fails and the test fails at that point.
🧠 Conceptual
advanced1:30remaining
Purpose of the @Test annotation in JUnit
What is the main purpose of the @Test annotation in a JUnit test class?
Attempts:
2 left
💡 Hint
Think about how JUnit knows which methods to execute as tests.
✗ Incorrect
The @Test annotation tells JUnit that the method is a test method to be executed during testing.
🔧 Debug
advanced2:00remaining
Identify the error in this JUnit test method
What error will occur when running this test class?
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class DebugTest { @Test void testDivision() { int result = 10 / 0; assertEquals(0, result); } }
Attempts:
2 left
💡 Hint
Division by zero is not allowed in Java and causes an exception.
✗ Incorrect
The code divides 10 by 0, which causes an ArithmeticException at runtime before the assertion is reached.
❓ framework
expert2:30remaining
Behavior of @Test with expected exception in JUnit 5
Consider this test method in JUnit 5. What is the test result?
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class ExceptionTest { @Test void testException() { assertThrows(IllegalArgumentException.class, () -> { throw new IllegalArgumentException("Invalid argument"); }); } }
Attempts:
2 left
💡 Hint
assertThrows expects the specified exception to be thrown inside the lambda.
✗ Incorrect
The lambda throws IllegalArgumentException as expected, so assertThrows passes and the test passes.