Labs
The String method public String substring(int beginIndex, int endIndex) returns a substring of a String instance. Create a new JUnit 5 (JUnit Jupiter) test case for this method, with test methods that:
- Test that
"abcdefg".substring(1, 5)returns"bcde". - Test that
"abcdefg".substring(0, 7)returns"abcdefg". - This method's purpose is to test that
beginIndexis inclusive andendIndexis exclusive (note that character7is thelength()of thisString). The method should state this purpose. - Test that
substringthrowsIndexOutOfBoundsException - if the
beginIndexis negative. - if
endIndexis larger than the length of thisStringobject. - if
beginIndexis larger thanendIndex. - The String specification says
substringthrowsIndexOutOfBoundsException; this is correct, according to the spec. - Test that the exception thrown by
substringis actuallyStringIndexOutOfBoundsException, a subclass ofIndexOutOfBoundsException.- Use the methods
getClass()andgetSimpleName()to get the exception's name.
- Use the methods
(Solution: SubstringTests.java)
Practice Exercise¶
The
substringspecification is correct becauseStringIndexOutOfBoundsExceptionIS-A subclass ofIndexOutOfBoundsException.Another JVM may throw
IndexOutOfBoundsException- not its subclass - and still comply with the spec.Therefore, if we are asked what
substringthrows, we sayIndexOutOfBoundsException.