Acero Ad
Acero Ad

Reputation: 23

How to obtain a field from my test in a Junit 5 jupiter extension

I have a Custom tag for my tests for a driver ive created. Im looking for a way to initialize and quit this driver during the BeforeEach and the AfterEach, using the new Junit5 jupiter extensions.

@Target({TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@ExtendWith(MyExtension.class)
public @interface MyDriver
{
} 

I've seen there is a AnnotationSupport.class that should help you to obtain the fields annotated with certain annotation but havent found any example.

What I want is just to be able to work with the field annotated with my annotation from the extension.

Upvotes: 1

Views: 2360

Answers (1)

johanneslink
johanneslink

Reputation: 5341

You could go about it like this:

public class MyExtension implements BeforeEachCallback {
    @Override
    public void beforeEach(ExtensionContext context)  {
        context.getTestInstance().ifPresent(testInstance -> {
            List<Field> driverFields = AnnotationSupport.findAnnotatedFields(testInstance.getClass(), MyDriver.class);
            for (Field driverField : driverFields) {
                try {
                    Object fieldValue = driverField.get(testInstance);
                    // Do whatever you want with the field or its value
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Which would then be called before each test in a test class like this:

@MyDriver
class SomeTestThatUsesDriver {

    @MyDriver
    Object fieldWithAnnotation = "whatever";

    @Test
    void aTest() {
       ...
    }
}

What I wouldn't do, though, is to use the annotation @MyDriver for both adding the extension and marking a field. I'd rather got with an additional annotation like @MyDriverField or add the extension directly at the test class.

Upvotes: 4

Related Questions