Home > Software engineering >  Branch & condition test Java
Branch & condition test Java

Time:06-26

I'm trying to do a branch & condition test on my code, it is very simple.

package testing;
import java.util.*;

public class Exercise1 {

private String s;

public Exercise1(String s) {
    
    if (s == null || s.length() == 0)
        throw new IllegalArgumentException("s == null || s.lenght() == 0");

    this.s = s;
  }
}

In branch and cond testing I have to check every single condition inside the code, so for example in my case I have to do the test when the string is expected to be null and size=0. I saw that i have to to this in my test class:

package testing
import static org.junit.*;
import org.junit.jupiter.api.Test;

class Exercise1Test{
    @Test(expected = IllegalArgumentException.class)
    public void stringNull() {
        new Exercise1(null);
    }    
}

Bur java doesn't recognize "expected". how can I check if the String is null so?

CodePudding user response:

@Test(expected = ...) can only be used with JUnit 4. JUnit 5 has Assertions.assertThrows as replacement. It allows you to assert that not just the entire test method throws an exception, but even small pieces of it. This has also been backported to JUnit 4.13.

Your test method would become this (using a static import for Assertions.assertThrows):

@Test
void stringNull() { // public not necessary in JUnit 5
    assertThrows(IllegalArgumentException.class, () -> new Exercise1(null));
}

But it gets better - assertThrows returns the exception that was thrown. It allows you to perform assertions on the exception after it has been thrown. It can be compared to JUnit 4's ExpectedException rule.

@Test
void stringNull() {
    IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> new Exercise1(null));
    assertEquals("s == null || s.lenght() == 0", thrown.getMessage());
}

A warning about using assertThrows: only use one method call inside it. For instance, for the following, you don't know what caused the IllegalArgumentException - the call to new Exercise, or the call to constructMessage.

assertThrows(IllegalArgumentException.class, () -> new Exercise1(constructMessage()));

It's advised to initialize such arguments before the call to assertThrows:

String message = constructMessage();
assertThrows(IllegalArgumentException.class, () -> new Exercise1(message));

On a side note, your imports are mixing JUnit 4 (org.junit.*) and JUnit 5 (org.junit.jupiter.api). Just drop the JUnit 4 ones.

  • Related