如果您需要使用 JUnit 来测试您的代码,请考虑这种方法。
这是 JUnit 测试应该如何工作的示例:
public class Factorial {
/**
* Calculates the factorial of the specified number in linear time and constant space complexity.<br>
* Due to integer limitations, possible calculation of factorials are for n in interval [0,12].<br>
*
* @param n the specified number
* @return n!
*/
public static int calc(int n) {
if (n < 0 || n > 12) {
throw new IllegalArgumentException("Factorials are defined only on non-negative integers.");
}
int result = 1;
if (n < 2) {
return result;
}
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class FactorialTest {
@Test
public void factorialOfZeroShouldBeOne() {
assertEquals(1, Factorial.calc(0));
}
@Test
public void factorialOfOneShouldBeOne() {
assertEquals(1, Factorial.calc(1));
}
@Test
public void factorialOfNShouldBeNTimesFactorialOfNMinusOne() {
for (int i = 2; i <= 12; i++) {
assertEquals(i * Factorial.calc(i - 1), Factorial.calc(i));
System.out.println(i + "! = " + Factorial.calc(i));
}
}
@Test(expected = IllegalArgumentException.class)
public void factorialOfNegativeNumberShouldThrowException() {
Factorial.calc(-1);
Factorial.calc(Integer.MIN_VALUE);
}
@Test(expected = IllegalArgumentException.class)
public void factorialOfNumberGreaterThanTwelveShouldThrowException() {
Factorial.calc(13);
Factorial.calc(20);
Factorial.calc(50);
}
}