public class PalindromeChecker {
/**
* Method that checks if a phrase or word is
* a Palindrome
*
* @param str
* Represents a string input
*
* @return true
* True if the string is a Palindrome,
* false otherwise
*/
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
str = str.toLowerCase();
String temp = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if ((ch >= '0' && ch <= '9') || (ch >= 'a'
&& ch <= 'z')) {
temp += ch;
}
}
if (str.length() <= 1) {
return true;
}
str = temp;
if (str.charAt(0) != str.charAt(str.length() - 1)) {
return false;
}
else {
return isPalindrome(str.substring(1, str.length() - 1));
}
}
}
Having the above code write Junit test in JAVA using assertEquals, assertTrue, assertFalse, etc. Make sure to test all possible outcomes and every line of code gets tested fully.
Below is the Junit Test Class TestPalindromeChecker for the class PalindromeChecker.
Covered all the possible scenarios. Please include Junit's latest version library while executing this code in your machine.
import static org.junit.Assert.*;
import org.junit.Test;
public class TestPalindromeChecker {
@Test
public void testIsPalindrome(){
assertFalse(PalindromeChecker.isPalindrome(null));//if
the str is null, then it should return false
assertTrue(PalindromeChecker.isPalindrome("L"));//if
str is one char length, it should return true
assertEquals(true,PalindromeChecker.isPalindrome("MALAYALAM"));
assertEquals(false,PalindromeChecker.isPalindrome("HMM"));
assertTrue(PalindromeChecker.isPalindrome("lol"));
assertFalse(PalindromeChecker.isPalindrome("not"));
}
}
Get Answers For Free
Most questions answered within 1 hours.