的东西,如果你需要使用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);
}
}
可以的,如果你想要断言你还可以添加你的“测试”代码 – radimpe 2012-07-13 07:44:06
一个参数你的方法不是null,这听起来像输入验证,而不是单元测试。这应该是班级发件人的一个断言。对于单元测试,您可以调用发件人类并查看它是否有效。 – Thilo 2012-07-13 07:44:45