0

I am trying to run a test on the class below:

package chapter03.backend;

import java.util.Map;

public class CharacterCounter {
    public static Map<Character, Integer> countCharacters(String text) {

         if (text == null) {
              throw new IllegalArgumentException("text must not be null");
            }
        return null;

    }
}

I have written this test class:

package chapter03.backend;

import static org.junit.Assert.*;

import org.junit.Test;

public class CharacterCounterTests {

    @Test(expected=IllegalAccessException.class)
    public void testNullInput() {
        CharacterCounter.countCharacters(null);
    }

}

When I run it, it keeps failing. Here is a screen shot of the error:

enter image description here

I will appreciate pointers on this.

1 Answer 1

2

IllegalAccessException is not IllegalArgumentException and is not a subclass of it either.

You throw indeed IllegalArgumentException in your tested method but you assert in the test that IllegalArgumentException is thrown.
Consequently, the assertion fails.

You should assert that IllegalArgumentException is expected:

@Test(expected=IllegalArgumentException.class)
public void testNullInput() {
    CharacterCounter.countCharacters(null);
}
3
  • Very very probably. Sometimes a copy paste is not so bad ;-)
    – davidxxx
    Commented Aug 16, 2017 at 18:43
  • It is a copy and paste! I apologize but a Java nubian. Not sure I understand the difference between what you pasted and what I have there
    – 0xsegfault
    Commented Aug 16, 2017 at 18:57
  • @Test(expected=IllegalAccessException.class) means that you expect that a IllegalArgumentException is thrown during the test method execution. But you never throw it in the tested code. You throw that : throw new IllegalArgumentException("text must not be null"). So Junit says you that your expected was not matched.
    – davidxxx
    Commented Aug 16, 2017 at 19:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.