Spring Boot with TestNG

Spring Boot is becoming an increasingly popular preconfigured Spring Framework. TestNG is also a very popular testing framework. Together Spring Boot and TestNG is a really powerful combination if you need to create a Test Automation Framework in Java.

In this post we’re going to see the minimal required code to get started with Spring Boot and TestNG.

TestNG + Spring Boot

This example can be considered as a start point for creating the Test Automation Framework if you choose Java, TestNG, Spring Boot and Maven as your tech stack.

Spring Boot and TestNG Maven dependencies

To make Spring Boot and TestNG work together you have to setup your pom.xml properly.

In your pom.xml you need to set spring-boot-starter-parent as a parent.

At the moment the current version of Spring Boot is 2.0.1.RELEASE.

Also you need to include 2 Spring Boot starters: spring-boot-starter, spring-boot-starter-test.

Finaly you should add TestNG as a dependency.

Spring Boot application class with main method

Just create that TestNGWithSpringApplication class with SpringBootApplication annotation in your highest level main (not test) package and forget about it.

AbstractTestNGSpringContextTests. Spring Boot + TestNG test class

The TestNG test class that contains your test methods. To make TestNG test class work with Spring Boot you should extend AbstractTestNGSpringContextTests and add @SpringBootTest annotation to the TestNG test class.

Now you can use @Autowire, @Value or any other features that Spring Boot gives you. You’re now able to inject already predefined Spring Boot beans or your own beans that you might want to create.

And the last. I usually extract all common methods, variables and constans into a separate class. In this case you can move Spring Boot and TestNG related class level annotations into that class like this:

Then your test class will look much better without these scary Spring Boot and TestNG things like SpringBootTest, AbstractTestNGSpringContextTests, TestNGWithSpringApplication.

Find more posts related to Spring Boot and TestNG by tags Spring Boot and TestNG

Spring Boot + TestNG Github Gists:


You may also find these posts interesting: