Search code examples
javajunitassertj

Assert that method does not throw an exception with AssertJ 1.x soft assertions


I would like to test that a particular method can handle a bunch of strings without an exception. Therefore, I would like to use AssertJ's soft assertions, something like:

SoftAssertion softly = new SoftAssertion();

for (String s : strings) {
    Foo foo = new Foo();

    try {
        foo.bar(s);
        // Mark soft assertion passed.
    } catch (IOException e) {
        // Mark soft assertion failed.
    }
}

softly.assertAll();

Unfortunately, I have to stick to AssertJ 1.x respectively Java 6, so I cannot take advantage of this:

assertThatCode(() -> {
    // code that should throw an exception
    ...
}).doesNotThrowAnyException();

Is there a way do this with AssertJ (or JUnit)?


Solution

  • I would say it's not a good practice to have a loop in the test code.

    If code you run inside a test throws an exception - it fails the test. My suggestion would be to use a Parameterized runner for JUnit (shipped with the library).

    Example from official JUnit 4 documentation:

    import static org.junit.Assert.assertEquals;
    import java.util.Arrays;
    import java.util.Collection;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.Parameterized;
    import org.junit.runners.Parameterized.Parameters;
    
    @RunWith(Parameterized.class)
    public class FibonacciTest {
        @Parameters
        public static Collection<Object[]> data() {
            return Arrays.asList(new Object[][] {     
                     { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }  
               });
        }
    
        private int fInput;
    
        private int fExpected;
    
        public FibonacciTest(int input, int expected) {
            fInput= input;
            fExpected= expected;
        }
    
        @Test
        public void test() {
            // Basically any code can be executed here
            assertEquals(fExpected, Fibonacci.compute(fInput));
        }
    }
    
    public class Fibonacci {
        public static int compute(int n) {
            int result = 0;
    
            if (n <= 1) { 
                result = n; 
            } else { 
                result = compute(n - 1) + compute(n - 2); 
            }
    
            return result;
        }
    }