Get startedGet started for free

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

View Course

Exercise instructions

  • Enter the correct reversed value for the input number.
  • Invoke the IntReverser method reverse() to acquire the actual value.
  • JUnit expects the expected/actual values in a specific order. Enter them into assertEquals().

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);
    }
}
Edit and Run Code