Kotlinlearncs.online LogoJava
Return to List

Test Writing: String Length Comparable

Created By: Geoffrey Challen
/ Version: 2020.10.0

Create a public class named MyString. MyString should provide a public constructor that accepts a single String argument and rejects null Strings. Your string variable should be private.

MyString should also implement the Comparable interface. 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". Note that you should implement Comparable<MyString>, meaning that MyString instances can be compared with other MyString instances but not with other objects. As a result, the signature of compareTo will be fun compareTo(other: MyString): Int, accepting a MyString rather than an Any.

You will probably need to review the documentation for Comparable.

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 Kotlin's assert or check methods