Applying TDD to reverse a number
You've seen Test-Driven Development — now let's apply it! Consider a simple method to reverse an int
. If you think in terms of TDD, the first thing you need to do is write a test. Focus on the behavior (input and output) of the method, not on its implementation. This will train you to put the project requirements first.
In the code snippet below, complete the test with the expected output, the expression to obtain the method's actual output, and the expression inside the assertEquals()
statement.
This exercise is part of the course
Introduction to Testing in Java
Exercise instructions
- Enter the correct reversed value for the input number.
- Invoke the
IntReverser
methodreverse()
to acquire the actual value. - JUnit expects the
expected
/actual
values in a specific order. Enter them intoassertEquals()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import org.junit.jupiter.api.Test;
import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchTestsAndPrint;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IntReverser {
public static int reverse(int input) {
return 0;
}
public static class IntReverserTest {
@Test
public void testReverse_reversesNumber() {
int input = 1234;
// Write down the expected return value
int expected = ____;
// Call the reverse() method to obtain its actual return value
int actual = ____;
// Write the arguments for the assert statement in the correct order
assertEquals(____);
}
}
public static void main(String[] args) {
launchTestsAndPrint(IntReverserTest.class);
}
}