package BasicTesting;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Factorial_of_number {
public static int factorial(int n)//factorial method
{
if (n == 0) {
return 1;
} else if (n < 1) {
return -1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number to factorize ");
int n = input.nextInt();
System.out.println(factorial(n));
}
}
Here, when we give negative numbers as input, they are not handled well. Actually, the program should return that we can't find factorial for negative numbers. By using this program, how can we write JUnit test cases to check whether the program give correct output for negative numbers? They are not checking negative numbers, so the system must fail while we test for exceptions, right? I am attaching my JUnit test case also.
package BasicTesting;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class FactorialTest {
public FactorialTest(int input, int expected) {
super();
this.input = input;
this.expected = expected;
}
Factorial_of_number ob = new Factorial_of_number();
private int input;
private int expected;
@Parameters
public static Iterable<Object[]> testConditions() {
return Arrays.asList(new Object[][]{{0, 1}, {1, 1},
{5, 120}, {-3, -1}, {10, 3628800}, {12, 479001600}});
}
@Test
public void factorial_test() {
assertEquals(expected, Factorial_of_number.factorial(input));
}
}
How can I check for that exception? Should I change my source program too? Kindly provide the edited code also.