使用 MethodSource 处理数字
和大多数历史悠久、广受欢迎的编程语言一样,Java 拥有庞大的生态系统,同一件事往往有多种写法。
回顾上一课中的 LastDigit 练习。请用 @MethodSource 重写它,借此练习本课介绍的语法。
本练习是课程的一部分
Java 测试入门
练习说明
- 使用正确的注解来编写一个参数化测试,使其参数来自某个方法。
- 将该注解指向参数提供者方法。
- 使用相同的语法三次来创建参数对。
交互式实操练习
通过完成这段示例代码来试试这个练习。
public class LastDigitWithTests {
public static void main(String[] args) {
launchTestsAndPrint(LastDigitTest.class);
}
}
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 argument objects for the test using the same syntax
____.of(2025, 5),
____.of(-2025, 5),
____.of(2020, 0)
);
}
}