json-snapshot.github.io icon indicating copy to clipboard operation
json-snapshot.github.io copied to clipboard

[JUnit 5] Add support for nested tests

Open grimsa opened this issue 6 years ago • 2 comments

Nested test docs: https://junit.org/junit5/docs/current/user-guide/#writing-tests-nested

Currently snapshot matching within nested test classes is not supported.

Example:

class Demo {
    @BeforeAll
    static void beforeAll() {
        SnapshotMatcher.start();
    }

    @AfterAll
    static void afterAll() {
        SnapshotMatcher.validateSnapshots();
    }

    @Test
    void one() {
        expect("one").toMatchSnapshot();       // succeeds
    }

    @Nested
    class NestedTest {
        @Test
        void two() {
            expect("two").toMatchSnapshot();         // fails
        }

        @Nested
        class DeeplyNestedTest {
            @Test
            void three() {
                expect("three").toMatchSnapshot();       // fails
            }
        }
    }
}

Stack trace:

io.github.jsonSnapshot.SnapshotMatchException: Could not find method two on class class java.lang.Object
Please annotate your test method with @Test and make it without any parameters!

	at io.github.jsonSnapshot.SnapshotMatcher.lambda$getMethod$4(SnapshotMatcher.java:174)
	at java.util.Optional.orElseThrow(Optional.java:290)
	at io.github.jsonSnapshot.SnapshotMatcher.getMethod(SnapshotMatcher.java:172)
	at io.github.jsonSnapshot.SnapshotMatcher.lambda$getMethod$3(SnapshotMatcher.java:171)
	at java.util.Optional.map(Optional.java:215)
	at io.github.jsonSnapshot.SnapshotMatcher.getMethod(SnapshotMatcher.java:171)
	at io.github.jsonSnapshot.SnapshotMatcher.expect(SnapshotMatcher.java:99)

grimsa avatar Jul 18 '19 14:07 grimsa

just stumbled on this issue too. are there any "workarounds"?

teosarca avatar Jul 13 '22 10:07 teosarca

@teosarca You may want to look at this fork https://github.com/origin-energy/java-snapshot-testing - it is maintained (unlike this project) and supports nested tests. We have recently switched to it in my project and so far everything works smoothly.

grimsa avatar Jul 13 '22 12:07 grimsa