Digits with MethodSource
Like most old and popular programming languages, Java has a huge ecosystem and there are many ways to do one thing.
Consider the LastDigit
exercise from the previous lesson. Practice the lesson's syntax by rewriting it using @MethodSource
.
This exercise is part of the course
Introduction to Testing in Java
Exercise instructions
- Use the correct annotation for a parameterized test that takes its arguments from a method.
- Point the annotation to the arguments provider method.
- Use the same syntax three times to create argument pairs.
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 java.util.List;
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
// Add the annotation to use a method to provide arguments and point it to the arguments method
@____("____")
void testLastDigit(int number, int expected) {
int actual = LastDigit.lastDigit(number);
assertEquals(expected, actual);
}
private static List getArgs() {
return List.of(
// Create three arguments objects for the test using the same syntax
____(2025, 5),
____(-2025, 5),
____(2020, 0)
);
}
}