Get startedGet started for free

CsvSource: Digits

You've revisited the lastDigit() from Chapter 1, and this time you've prepared for negative values using Math.abs(). Now that you know you can condense tests using @ParameterizedTest, you've attempted to test all outcomes of lastDigit() in one go.

Verify the method returns the correct digit for positive, negative, and zero-ending integers.

This exercise is part of the course

Introduction to Testing in Java

View Course

Exercise instructions

  • Use the annotation for inputting multiple values into a test method.
  • Add the method arguments for the test method.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.*;

import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchTestsAndPrint;
import static org.junit.jupiter.api.Assertions.*;

public class LastDigitWithTests {
  public static void main(String[] args) {
    launchTestsAndPrint(LastDigitTest.class);
  }
}

class LastDigit {
    public static int lastDigit(int a) {
        return Math.abs(a) % 10;
    }
}

class LastDigitTest {

    @ParameterizedTest
    // Use the correct annotation for a pair of integer inputs
    ____(value = {"2025, 5", "-2025, 5", "2020, 0"}) 
    // Write the corresponding argument types for the test method
    void testLastDigit(____ number, ____ expected) {
        int actual = LastDigit.lastDigit(number);

        assertEquals(expected, actual);
    }
}
Edit and Run Code