Alex Biddle     About     Archive     Feed

Create dataprovider tests in Spring Boot 1.4

When writing tests, you may find yourself testing a piece of functionality, like validation, where you need to provide many inputs and assert against many outputs without changing the structure of the test.

Instead of copy and pasting tests, dataproviders call your test methods with parameters that you can use as inputs and assertions. TestNG and phpunit follow roughly the same syntax. JUnit does something slightly different with its parametised tests, which work on a class, rather than method level.

There is, however, the junit-dataprovider library which provides a “A TestNG like dataprovider runner for JUnit”.

<dependency>
	<groupId>com.tngtech.java</groupId>
	<artifactId>junit-dataprovider</artifactId>
</dependency>

I created a Spring Boot 1.4 integration with this library that you can checkout and run.

To integrate the library, you have to annotate your test classes with the dataprovider runner.

@RunWith(DataProviderRunner.class)
@SpringBootTest
@WebAppConfiguration
public class DataproviderApplicationTests

Next you have to add the Spring class and method rules as member variables.

@ClassRule
public static final SpringClassRule springClassRule = new SpringClassRule();

@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();

Finally you can use the dataprovider syntax you are familiar with. There are many options in the documentation, here’s a simple case I used for the demo project:

@DataProvider
public static Object[][] localeProvider() {
	return new Object[][] {
			{ Locale.ENGLISH, "Hello" },
			{ Locale.GERMAN, "Guten Tag" },
			{ Locale.FRENCH, "Bonjour" }
	};
}

@Test
@UseDataProvider("localeProvider")
public void testMessageSources(Locale locale, String message) {
	assertThat(messageSource.getMessage("hello", null, locale), is(message));
}