Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
JUnit5: access extension field from test class

I need to use extensions to run code before and after all test cases in classes that use it. My test classes need to access a field in my Extension class. Is this possible?

Given:

@ExtendWith(MyExtension.class)
public class MyTestClass {
    
    @Test
    public void test() {
        // get myField from extension and use it in the test
    }
}

and

public class MyExtension implements 
  BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback {
    
    private int myField;

    public MyExtension() {
        myField = someLogic();
    }

    ...
}

How do I access myField from my test class?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can achieve this via a marker annotation and a BeforeEachCallback extension.

Create a special marker annotation, e.g.

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyField {
}

Use the annotation to find and set the values from within the extension:

import org.junit.jupiter.api.extension.BeforeEachCallback;

public class MyExtension implements BeforeEachCallback {

    @Override
    public void beforeEach(final ExtensionContext context) throws Exception {
        // Get the list of test instances (instances of test classes) 
        final List<Object> testInstances = 
            context.getRequiredTestInstances().getAllInstances();
        
        // Find all fields annotated with @MyField
        // in all testInstances objects.
        // You may use a utility library of your choice for this task. 
        // See for example, https://github.com/ronmamo/reflections 
        // I've omitted this boilerplate code here. 

        // Assign the annotated field's value via reflection. 
        // I've omitted this boilerplate code here. 
    }

}

Then, in your tests, you annotate the target field and extend the test with your extension:

@ExtendWith(MyExtension.class)
public class MyTestClass {

    @MyField
    int myField;

    @Test
    public void test() {
        // use myField which has been assigned by the extension before test execution
    }

}

Note: you can alternatively extend BeforeAllCallback which is executed once before all test methods of the class, depending on your actual requirements.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda