lundi 22 mars 2021

Spring accessing child elements via the ExtendWith annotation from the parent?

Maybe someone can tell me my setup is terrible. I'm writing some utilities to ease our integration testing efforts to reduce the amount of duplicate code for before/after methods of our integration tests.

IE - blowing away data in a database.

I can have N number of test harness classes dependning on which containers are required for the integration test.

I want to be able to run something like client.clearDatabase but from the parent class underneath the extendWith annotation. Obviously, I don't have access to client in this case and that is just a utility module. I'm wondering how I can think about this problem to do it correctly.

Test A

@SpringBootTest(classes = ClassImTesting.class)
@ExtendWith(TestHarnessUtility.class)
public class MyCoolIntegrationTest {
  @Autowired private Database client;

  // This is what I want to exist in the ExtendWith class.. ie - TestHarnessUtility, then I can reuse this and people don't need to always worry about duplicating this block of code
  @AfterEach
  public void testCleanup() {
    client.clearDatabase();
  }

Test Harness Class

/**
 * Automates the setup and configuration of all integration tests that require usage of the
 * Gremlin containers for Graph DB testing.
 */
public class TestHarnessUtility extends SuperTestHarnessUtility {

  @Override
  public void beforeAll(ExtensionContext context) {
    startTestsWithContainers(GREMLIN_SERVER);
    System
        .setProperty(GREMLIN_SERVER_KEY, SupportedContainers.gremlinServer.getContainerIpAddress());
    System.setProperty(GREMLIN_SERVER_PORT,
        String.valueOf(SupportedContainers.gremlinServer.getFirstMappedPort()));
  }

 @Override
  public void afterAll(ExtensionContext context) {
   // Method not implementented
 }

  @Override
  public void afterEach(ExtensionContext context) {
    // Method not implemented
 }
}

Super Test Harness Utility

public abstract class SuperTestHarnessUtility implements BeforeAllCallback, AfterAllCallback,
    AfterEachCallback {

  /**
   * Runs after all Spring tests execute - Cleans up the state for the next set.
   */
  @Override
  public void afterAll(ExtensionContext context) throws Exception {

  }

  /**
   * Runs after each Spring test executes - Cleans up the state for the next set.
   */
  @Override
  public void afterEach(ExtensionContext context) throws Exception {

  }


  /**
   * Runs before all Spring tests execute - Facilitates container initialization and environment
   * variable property injection.
   */

  @Override
  public void beforeAll(ExtensionContext context) throws Exception {

  }
}

Aucun commentaire:

Enregistrer un commentaire