Java - Spring unit test with custom provided configuration.

less than 1 minute read

The following example will show how to define the custom Spring configuration for unit test with @ContextConfiguration annotation.
Full example can be found the below github.

https://github.com/nsclass/java-timezone/blob/master/src/test/java/com/ns/timezone/javatimezone/JavaTimezoneServiceApplicationTests.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = JavaTimezoneServiceApplicationTests.AppConfig.class)
public class JavaTimezoneServiceApplicationTests
{
	@Configuration
	static class AppConfig
	{
		@Bean
		TimezoneService timezoneService() {
			return new TimezoneService();
		}
	}
	@Autowired
	private TimezoneService timezoneService;
	@Test
	public void verifyGetAllTimezoneDisplay() {
		Flux<TimezoneService.TimezoneDisplayInfo> timezones = timezoneService.getAllTimezoneDisplay();
		int count = timezones.collectList().block().size();
		Assert.assertEquals(627, count);
	}
}