当前位置: 首页 > 工具软件 > JUnitParams > 使用案例 >

zz测试接口_使用FizzBu​​zz和JUnitParams进行单元测试

司空繁
2023-12-01

zz测试接口

我有时使用FizzBu​​zz向新手演示单元测试的基础。 尽管FizzBu​​zz确实是一个简单的问题,但它也可以用于演示更高级的单元测试技术,例如实现参数化测试。

FizzBu​​zz的可能解决方案之一是:

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种测试方法,每种方法针对不同的FizzBu​​zz案例:

@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

翻译自: https://www.javacodegeeks.com/2014/11/unit-testing-exercise-with-fizzbuzz-and-junitparams.html

zz测试接口

 类似资料: