lundi 25 janvier 2021

Encounter issues when passing the exception tests

I'm very new to Java. The assignment is about extracting the first and last several characters from a string to a new one. My solution passes most tests. But I encountered issues when dealing with exception test.

Below is my code for solution.

public static String firstAndLastCharacters(String text, int count) {

    if( text.equals("")|| count < 0 || count > text.length()){
        throw new IllegalArgumentException();
    }

    StringBuilder result = new StringBuilder();

    result.append(text, 0, count);
    result.append(text.substring(text.length()-count));
    return result.toString();
}

Below is three exception tests I cannot pass.

   @Test
void should_throw_if_input_string_is_null() {
    final IllegalArgumentException exception = assertThrows(
        IllegalArgumentException.class, () -> StringHelper.firstAndLastCharacters(null, 0));
    assertEquals("The text cannot be null.", exception.getMessage());
}

@Test
void should_throw_if_count_is_negative() {
    final IllegalArgumentException exception = assertThrows(
        IllegalArgumentException.class, () -> StringHelper.firstAndLastCharacters("Hello", -1));
    assertEquals("Invalid count.", exception.getMessage());
}

@Test
void should_throw_if_count_is_greater_than_text_length() {
    final IllegalArgumentException exception = assertThrows(
        IllegalArgumentException.class, () -> StringHelper.firstAndLastCharacters("Hello", 100));
    assertEquals("Invalid count.", exception.getMessage());
}

I'm wondering how should I modify my code. If you think my code can be more simpler, you're welcome to comment as well. Thank you.

Aucun commentaire:

Enregistrer un commentaire