TestNG tests breakup into nested classes

17 hours ago 1
ARTICLE AD BOX

I have TestNG tests with long startup times (they init Spring, a complicated DB setup, etc.). What I now want is to boot up only once and then run many tests in one class.

To keep the test-class from becoming too large, I want to split it into external nested classes. Like this:

@ContextConfiguration(initializers = SuperComplicatedStuff.class) @SpringBootTest( classes = {Main.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) /* Important to clear context, or different tests with different database setups will destroy each other. */ @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class Container extends AbstractTestNGSpringContextTests { @Autowired private MyRepository myRepository; @Nested class DbIntegrationTestImpl extends DbIntegrationTest { DbIntegrationTestImpl() { /* Passing "this", so the implementing class can access all the autowired variables, like "myRepository". */ super(Container.this); } } } abstract class DbIntegrationTest { private final Container parent; public DbIntegrationTest(Container parent) { this.parent = parent; } @Test void testRepositories() { parent.myRepository.findById(id); } }

I have done something very similar already successfully with JUnit 5. I could even start DbIntegrationTestImpl tests directly from IntelliJ, and JUnit was smart enough to init the surrounding class correctly first (following all annotations).

If I use TestNGs @Factory I lose the ability to run a single test-class standalone, which I want to keep for fast, iterative Test-Driven-Development. Also, the main class destroys its Spring context before it starts the factory classes, which destroys the whole purpose of this task.

Is there any way to do this, or something similar, with TestNG 7.14?

Read Entire Article