0

This is a bit hard to explain, but the code should make it clear. I'm going through the Java koans (https://github.com/matyb/java-koans) to teach myself Java - they are fun by the way, I recommend them.

Anyway, the code has a bunch of assert statements you have to correct in order to complete the koans. Currently the two assert statements below are failing. I'm having trouble fixing the first one.

What's actually thrown is java.util.MissingFormatArgumentException. So e.getClass() will return that. But it returns an actual Class object, not a string. To make the assert statement succeed, I think I need to get a Class object for java.util.MissingFormatArgumentException. But I can't just create one because the Class class has no public constructor (see https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html).

Any ideas how to fix this assert? Simply removing it would be cheating. Fixing String.format() would also be cheating.

public void insufficientArgumentsToStringFormatCausesAnError() {
    try {
        String.format("%s %s %s", "a", "b");
        fail("No Exception was thrown!");
    } catch (Exception e) {
        assertEquals(e.getClass(), "");
        assertEquals(e.getMessage(), "");
    }
}
Stephen
  • 8,508
  • 12
  • 56
  • 96
  • 3
    `java.util.MissingFormatArgumentException.class` – shmosel Mar 07 '18 at 00:36
  • https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html – shmosel Mar 07 '18 at 00:36
  • Re your first comment - wow thanks, I didn't realize it was that easy. I had tried that but left off the java.util prefix, so it didn't work. – Stephen Mar 07 '18 at 00:37
  • Just import it if you don't want the prefix. – shmosel Mar 07 '18 at 00:38
  • *Any ideas how to fix this assert? Simply removing it would be cheating. Fixing String.format() would also be cheating.* What about `assertEquals(e.getClass(), e.getClass())`? – shmosel Mar 07 '18 at 00:39
  • Haha well I don't know. It's up to the player to define cheating I suppose. I like the first solution you provided best. I learned that it's possible to do that, which is the point of playing. – Stephen Mar 07 '18 at 00:41

0 Answers0