java-snapshot-testing icon indicating copy to clipboard operation
java-snapshot-testing copied to clipboard

Kotlin+Junit 5 Expect is not injected when using @Nested tests

Open ross-paypay opened this issue 2 years ago • 3 comments

When using nested tests, Expect is not injected into the outer class.

Example

@ExtendWith(SnapshotExtension::class)
class ExampleTest {

    lateinit var expect: Expect

    @Test
    fun foo() {
        expect.toMatchSnapshot("foo")
    }

    @Nested
    inner class MyNestedTest {
        @Test
        fun bar() {
            expect.toMatchSnapshot("bar") // Nullpointer `expect` is null
        }
    }
}

This can be worked around by defining expect in the inner class

Work around example
@ExtendWith(SnapshotExtension::class)
class ExampleTest {

    lateinit var expect: Expect

    @Test
    fun foo() {
        expect.toMatchSnapshot("foo")
    }

    @Nested
    inner class MyNestedTest {
        lateinit var expect: Expect
        @Test
        fun bar() {
            expect.toMatchSnapshot("bar") // Nullpointer `expect` is null
        }
    }
}

Personally, I think it would be the most intiutive / least boilerplate to inject at the class with the @ExtendWith(SnapshotExtension.class) annotation. Or maybe if possible, walk the class tree and inject into all classes.

ross-paypay avatar Sep 18 '23 12:09 ross-paypay

Confirming this issue on Java+JUnit5. Thanks @ross-paypay for pointing out the workaround.

Another workaround is to use injected field, which unfortunately reports that it is deprecated for removal in v5, so that is not a stable way forward.

Philzen avatar Oct 24 '23 02:10 Philzen

It seems like the issue is not restricted to Kotlin. I have the same problem using java.

cponfick avatar Jul 12 '24 10:07 cponfick

I have a test for this is sure enough, expect is part of the nested class

https://github.com/origin-energy/java-snapshot-testing/blob/master/java-snapshot-testing-junit5/src/test/java/au/com/origin/snapshots/NestedClassTestWithExtends.java#L28

jackmatt2 avatar Aug 08 '24 07:08 jackmatt2