In: Computer Science
For Java
Let's get more practice testing! Declare a public class TestRotateString with a single void static method named testRotateString. testRotateString receives an instance of RotateString as a parameter, which has a single method rotate. rotate takes a String and an int as arguments, and rotates the passed string by the passed amount. If the amount is positive, the rotation is to the right; if negative, to the left. If the String is null, rotate should return null.
Your testRotateString method should test the passed implementation using assert. Here's an example to get you started:\
assert rotate.String.rotate(null, 0) == null;
As you create your test suite, consider the various kinds of mistakes that you might make when implementing rotate. Maybe getting the direction wrong, or using the modulus improperly? There are lots of ways to mess this up! You need to catch all of them. Good luck!
First we declare the rotate method in RotateString class
public class RotateString
{
public String rotate(String string, int rotations) {
if (string == null)
return null;
if (rotations == 0)
return string;
int size = string.size();
rotations %= size;
if (rotations < 0) {
return string.substring(rotations) + string.substring(0, rotations);
}
return string.substring(size - rotations) + string.substring(0, size - rotations);
}
}
Now we check all possible edge cases for rotate method
We check if passed argument is an instance of RotateString or not
We check outputs for null string, empty string
We validate rotation for positive and negative values
We vaildatte repeated rotations that is when rotations are greater than size of string
TestRotateString.java
public class TestRotateString
{
static void testRotateString(RotateString rotateString) {
assert (rotateString instanceof RotateString) == true;
assert rotateString.rotate(null, 4) == null;
assert rotateString.rotate("", 100) == "";
assert rotateString.rotate("hello", 1) == "elloh";
assert rotateString.rotate("hello", -1) == "ohell";
assert rotateString.rotate("hello", 2) == rotateString.rotate("hello", 7);
assert rotateString.rotate("hello", -2) == rotateString.rotate("hello", -7);
}
}