skinny85 / specnaz

Library for writing beautiful, RSpec/Jasmine/Mocha/Jest-style specifications in Java, Kotlin and Groovy
Other
34 stars 8 forks source link

Support tests expecting Exceptions #2

Closed skinny85 closed 7 years ago

skinny85 commented 7 years ago

In "regular" JUnit, you can write a test like so:

import org.junit.Test;

import java.util.ArrayList;

public class ExpectTest {
    @Test(expected = IndexOutOfBoundsException.class)
    public void expect_exception_test() throws Exception {
        new ArrayList<String>().get(0);
    }
}

There was a Feature Request to add a similar capability to Specnaz.

skinny85 commented 7 years ago

The reason I'm not in love with this feature is that I never liked the JUnit's expect attribute. In my opinion, the tests are less readable with it, and a lot more fragile (I've often seen tests that passed, but the actual Exception was not thrown from the line that the author intended, and so they were in fact 'false positives').

As long as Specnaz doesn't have this feature, it forces people to look for alternatives - which is great, because a lot of alternatives exist, and they are all better than JUnit's expect:

Design-wise, I don't see a problem with this feature. I would probably make the API look something like:

it.shoudThrow(IllegalArgumentException.class, "when called with a null argument", () -> {
    // the test name will be: "should throw IllegalArgumentException when called with a null argument"
    // ...
});

The perfect API would probably be:

it.shouldThrow<IllegalArgumentException>("when called with a null argument", () -> {
    // ...
});

..but I'm not sure that's possible with Java. I do know that KotlinTest does something like this, so perhaps that will be the API in the Kotlin version.

The only question is: do we want to do this, or do we rather skip this, forcing people to look for (better) alternatives?

skinny85 commented 7 years ago

Fixed in 1.1 - resolving.