Freewind Freewind - 6 months ago 9
Java Question

How can I use strings to describe test cases in Java?

With JUnit, the description of my test cases would normally in the method name, like:

@Test
public void should_return_6_if_distance_is_2km() {
}


or

@Test
public void shouldReturn6IfDistanceIs2km() {
}


Which is not quite readable.

But with the testing frameworks of other lanuage, like javascript, or scala, I can use:

describe("Taximeter") {
it("should return 6 if the distance is 2km") {
...
}
}


which is more readable with plain strings.

Is it possible to do this in Java?

Answer

Spectrum is quite close to my requirement:

@RunWith(Spectrum.class)
public class ExampleSpec {{

    describe("A spec", () -> {

        final int foo = 1;

        it("is just a code block with a run() method", new Block() {
            @Override
            public void run() throws Throwable {
                assertEquals(1, foo);
            }
        });

        it("can also be a lambda function, which is a lot prettier", () -> {
            assertEquals(1, foo);
        });

        it("can use any assertion library you like", () -> {
            org.junit.Assert.assertEquals(1, foo);
            org.hamcrest.MatcherAssert.assertThat(true, is(true));
        });

        describe("nested inside a second describe", () -> {

            final int bar = 1;

            it("can reference both scopes as needed", () -> {
                assertThat(bar, is(equalTo(foo)));
            });

        });

        it("can have `it`s and `describe`s in any order", () -> {
            assertThat(foo, is(1));
        });

    });
}