Skip to content

Parameterized BeforeEach or AfterEach only #3157

@sbernard31

Description

@sbernard31

My need :

I have a class containing several tests.
I have a @BeforeEach and @AfterEach which setup and tear down each tests.

Now I would like to parameterize test but I don't want to get param on test method but only on @BeforeEach method.

Here is a very simplified example of code of what I would like to do :
(In my real use case, my start() method is far more complicated with more than one object to initialize and more than 1 argument as parameter)

public class TestSuite {
     
    private MyObjectToTest objectToTest;
     
    @ParameterizedForEach(name = "My custom name {}")
    @ValueSource(strings = { "param1", "param2", "param3"})
    @BeforeEach
    public void start(String param) {
        objectToTest = new MyObjectToTest(param);
    }

    @AfterEach
    public void stop() throws InterruptedException {
        objectToTest.destroy();
    }

    @Test
    public void test1() {
        assertThat(objectToTest).isValid();
    }

    @Test
    public void test2() {
        assertThat(objectToTest).isOK();
    }

My solution for now :

I used the CustomParameterResolver way described at

but this does not reallly elegant as I need to add argument to test method too.
This looks like :

@ExtendWith(CustomParameterResolver.class)
public class TestSuite {

    @ParameterizedTest(name = "My custom name {}")
    @ValueSource(strings = { "param1", "param2", "param3"})
    @Retention(RetentionPolicy.RUNTIME)
    private @interface TestAllParams {
    }

    private MyObjectToTest objectToTest;
     
    @BeforeEach
    public void start(String param) {
        objectToTest = new MyObjectToTest(param);
    }

    @AfterEach
    public void stop() throws InterruptedException {
        objectToTest.destroy();
    }

    @TestAllParams
    public void test1(String param)  {
        assertThat(objectToTest).isValid();
    }

    @TestAllParams
    public void test2(String param)  {
        assertThat(objectToTest).isOK();
    }

Question ?

Do you think this feature request make sense ?
Any advice to achieve this in a better / more elegant way ?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions