I am setting up some practical exams and require implementation of certain methods to be recursive. Is there a way for the JUnit test to pass only if the implementation of the method is recursive (and correct, of course)?
I have tried using getStackTrace()
but I couldn't find a way to get the methods calls made earlier in the program. (Because if I can do that, I can check if containsDigit
in the following example is being called the required number of times)
MWP
import static org.junit.Assert.*;
import org.junit.*;
import java.io.*;
import java.text.*;
import java.util.*;
import org.junit.rules.*;
import java.lang.reflect.*;
public class Service { //begin class
/**
* @param n: assumed to be more than 0
* @param d, d >= 0 and d <= 9
* @return true if number n contains the digit d, false otherwise
* you may assume that 0 itself doesn't contain ANY digit (not even 0)
* NOTE: This method must be implemented recursively.
* hint: n%10 gives the last digit, n/10 gives the rest of the number
*/
public static boolean containsDigit(int n, int d) {
return false; //to be completed
}
@Test
public void testContainsDigit() {
assertTrue(Service.containsDigit(1729, 1));
assertTrue(Service.containsDigit(1234567890, 2));
assertFalse(Service.containsDigit(1729, 8));
}
}
I would like the test to pass for a recursive implementation like:
public static boolean containsDigit(int n, int d) {
if(n == 0)
return false;
if(n%10 == d)
return true;
return containsDigit(n/10, d);
}
and fail for an iterative (even if correct) implementation like:
public static boolean containsDigit(int n, int d) {
while(n > 0) {
if(n%10 == d) {
return true;
}
n/=10;
}
return false;
}
Any help, or guidance in the right direction would very much be appreciated.