我有时使用FizzBuzz向新手演示单元测试的基础。 尽管FizzBuzz确实是一个简单的问题,但它也可以用于演示更高级的单元测试技术,例如实现参数化测试。
FizzBuzz的可能解决方案之一是:
public class FizzBuzz {
private static final int THREE = 3;
private static final int FIVE = 5;
public String calculate(int number) {
if (isDivisibleBy(number, THREE) && isDivisibleBy(number, FIVE)) {
return "FizzBuzz";
}
if (isDivisibleBy(number, THREE)) {
return "Fizz";
}
if (isDivisibleBy(number, FIVE)) {
return "Buzz";
}
return String.valueOf(number);
}
private boolean isDivisibleBy(int dividend, int divisor) {
return dividend % divisor == 0;
}
}
上面的示例非常适合显示JUnitParams的参数化测试。 我们可以创建4种测试方法,每种方法用于不同的FizzBuzz案例:
@Test
@Parameters({"1", "2", "4", "7", "11", "13", "14"})
public void returnsNumberForNumberNotDivisibleByThreeAndFive(int number) {
assertThat(fizzBuzz.calculate(number)).isEqualTo("" + number);
}
@Test
@Parameters({"3", "6", "9", "12", "18", "21", "24"})
public void returnFizzForNumberDivisibleByThree(int number) {
assertThat(fizzBuzz.calculate(number)).isEqualTo("Fizz");
}
@Test
@Parameters({"5", "10", "20", "25", "35", "40", "50"})
public void returnBuzzForNumberDivisibleByFive(int number) {
assertThat(fizzBuzz.calculate(number)).isEqualTo("Buzz");
}
@Test
@Parameters({"15", "30", "45", "60"})
public void returnsFizzBuzzForNumberDivisibleByThreeAndFive(int number) {
assertThat(fizzBuzz.calculate(number)).isEqualTo("FizzBuzz");
}
但是我们也可以用一种参数化的测试方法涵盖所有情况:
@Test
@Parameters
public void fizzBuzz(int given, String expected) {
assertThat(fizzBuzz.calculate(given)).isEqualTo(expected);
}
public Object[] parametersForFizzBuzz() {
return $(
$(1, "1"),
$(2, "2"),
$(3, "Fizz"),
$(4, "4"),
$(5, "Buzz"),
$(6, "Fizz"),
$(7, "7"),
$(10, "Buzz"),
$(15, "FizzBuzz"),
$(30, "FizzBuzz")
);
}
享受JunitParams !
- 看一下介绍单元测试不同方面的unit-testing-demo项目,包括参数化测试: https : //github.com/kolorobot/unit-testing-demo
翻译自: https://www.javacodegeeks.com/2014/11/unit-testing-exercise-with-fizzbuzz-and-junitparams.html