junit-pioneer / junit-pioneer

JUnit 5 Extension Pack
https://junit-pioneer.org
Eclipse Public License 2.0
534 stars 74 forks source link

`@Shared` resources with parameters #808

Open Michael1993 opened 5 months ago

Michael1993 commented 5 months ago

I think this should be a relatively simple addition. Currently, our documentation says:

We do not support creating shared resources with arguments. This is because if a test refers to a shared resource with the name "Foo" without arguments, then later another test refers to it with one argument, there is no reasonable way to fulfill that request. Furthermore, even if this was supported, the behavior would change if the first and second tests ever ran in opposite order, which is very likely when tests are configured to run in parallel.

But I think we can support it with something like this:

@Shared(factory = FooResourceFactory.class, name = "sharedFoo1", parameters = { "p1", "p2" })
@Shared(factory = FooResourceFactory.class, name = "sharedFoo2", parameters = { "p3", "p4" })
class FooTests {

    @Test
    void test1(@Shared.Named("sharedFoo1") Foo foo) {
        // test here...
    }

    @Test
    void test2(@Shared.Named("sharedFoo1") Foo foo) {
        // test here...
    }

    @Test
    void test3(@Shared.Named("sharedFoo2") Foo foo) {
        // test here...
    }

    @Test
    void test4(@Shared.Named("sharedFoo2") Foo foo) {
        // test here...
    }

}

We would create the resource before the tests and then just take it from the class-scoped ExtensionContext.Store. This does not solve (of course) how to share resources with parameters that have Scope.GLOBAL.

Bukama commented 5 months ago

I'm a bit confused by the example/idea: Do the classes of the @Shared resources be the same or can be different. I guess they can be whatever they want?

Michael1993 commented 5 months ago

Yeah, if they have different names and/or factory classes, they can be whatever.