Digits of a number
Consider the last digit of a number method that we encountered in the previous lesson. This method uses % 10
to grab
the last digit of an integer.
Write a PASSING test that illustrates that this method works for a given integer value.
This exercise is part of the course
Introduction to Testing in Java
Exercise instructions
- Enter the correct annotation that will enable JUnit to execute this test.
- Enter the expected last digit of the provided integer.
- Use the correct JUnit assertion to assert equality between the expected and actual values.
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.*;
public class LastDigitWithTests {
public static void main(String[] args) {
launchTestsAndPrint(LastDigitTest.class);
}
}
class LastDigit {
public static int lastDigit(int a) {
return a % 10;
}
}
class LastDigitTest {
// Use the correct annotation to mark this as a JUnit test
____
void testLastDigit() {
int number = 2025;
// What is the expected output?
int expected = ____;
int actual = LastDigit.lastDigit(number);
// Use the correct JUnit assertion for the scenario
____(expected, actual);
}
}