简体   繁体   中英

Creating a configurable JUnit library to test same features across several microservices

A set of tests should be run on every microservice. Current solution is to have an abstract class and extend in every service, providing the necessary properties in abstract getters.

public abstract class AbstractTest {

    @LocalServerPort
    protected int serverPort;

    protected abstract String getPath();
 
    @Test
    void someTest() {}

    @Test
    void conditionalTest() {}
}

@SpringBootTest(
    webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
    classes = {...})
@ActiveProfiles(...) // etc
public class MyTest extends AbstractTest {
// ... implement getPath()
// tests from parent will be executed
}

The goal: Ditch inheritance and have the AbstractTest 's logic get executed automatically with conditional @Test execution based on beans/properties etc.

The possible solution: A concrete class with all the tests or some sort of Configuration/TestFactory to create the necessary tests. It should take into account available properties and beans to determine which tests to run.

The problem: How can those tests (created in runtime) be discovered and registered for execution? How to inject all the properties that are part of the current context of the @SpringBootTest ?

Failed attempts:

  • TestInstanceFactory extension doesn't seem to be the solution as it requires an instance of the class which it annotates.
  • Using the Launcher API seems overkill, and also doesn't seem to work, since the library class won't be created with the Spring context configs.
  • using cglib and a base class Spring Contract -style is not a desirable solution

Ideally I don't want the client of this lib to implement/create anything, so abstract String getPath(); would be a test.lib.path property, and if it's present, a test from the library which uses it will run.

Any thoughts on this would be great, because right now this just seems impossible to me.

What is the reason to have the inheritance for tests? In case you need to share some common logic within the tests you may try JUnit features (custom rules/extensions), for example

  1. For junit < 5.xx @Rule functionality https://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html https://stackoverflow.com/a/34608174/6916890
  2. For junit >= 5.xx (jupiter) there is an extension API https://junit.org/junit5/docs/current/user-guide/#writing-tests-built-in-extensions-TempDirectory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM