0

I just have a quick question about test classes in IntelliJ. My task is to "Write a test method that verifies that the method works as you expect."

This is the method to test:

public int MatchNumber(char[] input, char c) {
 int number = 0;
        for (int i = 0; i < input.length; i++) {
            if (input[i] == c) {
                number++;
            }
        }
        return number;
    }
}

I'm not too sure how exactly test classes work in Java so if somebody could put me on the right lines then I'd be very thankful. Thanks in advance.

Kirby
  • 15,127
  • 10
  • 89
  • 104
user3080698
  • 61
  • 1
  • 1
  • 9

2 Answers2

1

Simply saying: use JUnit, then one of your tests can look like:

@Test
public void shouldMatchNumber() {

    // given
    char[] input = { 'a', 'b', 'c', 'd', 'a' };
    char c = 'a';

    // when
    int result = object.MatchNumber(input, c);

    // then
    assertEquals(2, result);
}
k0ner
  • 1,086
  • 7
  • 20
  • Ok that explains a lot. Thank you. One problem I have now though is the fact that assertequals and object are highlighted in red and I'm not sure why. Any ideas? Thanks. – user3080698 Dec 04 '15 at 22:48
  • `object` is the object which holds `MatchNumber` method - the name of instance you are using. Please read carefully Junit.org. – k0ner Dec 04 '15 at 22:50
  • and `assertEquals` is red because probably you haven't added `junit` library: https://github.com/junit-team/junit/wiki/Download-and-Install – k0ner Dec 04 '15 at 22:51
  • I managed to solve the issue with assertEquals but for some reason I still can't get rid off the object error. I'll have to try some other things. Thanks anyway. – user3080698 Dec 04 '15 at 23:14
  • to get rid off `object` error you have to instantiate your class `YourClass object = new YourClass()`. `YourClass` is the class which holds `MatchNumber` method – k0ner Dec 04 '15 at 23:17
0

You can think of test classes of "specifications". If your class fails on the test, then it does not pass the specification. What you expect your method to do is, apparently, to return the number of occurrences of c in input. So write test methods that do a reasonably well job to verify this. Test it against aaaa and a, and verify, that it is 4. Test it against aaaab and a, and verify, that it is 4. Test it against aaaa and b, and verify that it is 0. And so on.

Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45