Kotlinlearncs.online LogoJava
Return to List

Test Writing: String Length Comparable

Created By: Geoffrey Challen
/ Version: 2020.10.0

Let's get some practice implementing a known interface. Create a public class named MyString. MyString should provide a public constructor that accepts a single String argument. You should reject null Strings in your constructor using assert.

MyString should also implement the Java Comparable interface, returning 1 for a positive result and -1 for a negative result. Normally Strings are compared lexicographically: "aaa" comes before "z". MyString should compare instances based on the length of its stored String. So MyString("aaa") should come after MyString("z"), since "aaa" is longer than "z".

You will probably need to review the documentation for Comparable. Note that compareTo accepts an Object as an argument, but you can reject non-MyString arguments using assert.

Test Design Challenge

You're challenge is to write tests for this problem described above.

  • Provide a public class named TestMyString with a single non-private class method named test that accepts no arguments and does not return a value.
  • If the implementation of the class described above is incorrect, your test method should throw an exception.
  • If it is correct, do not throw an exception.
  • You may want to use Java's assert method