CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Introduction to Testing in Java

Afficher le cours

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().

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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);
    }
}
Modifier et exécuter le code