Spring Boot Unit Test Autowired

Since SpringBoot 1.4, all the classes changed and deprecated https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4.0-M2-Release-Notes. Replace the Runner and Configuration with the ones below. SpringRunner will detect the test framework for you.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { FileService.class, AppProperties.class, DownloadConfigEventHandler.class })
@EnableConfigurationProperties
public class ConfigMatrixDownloadAndProcessingIntegrationTests extends ConfigMatrixDownloadAbstractTest {

  // @Service FileService
  @Autowired
  private FileService fileService;

  // @Configuration AppProperties
  @Autowired
  private AppProperties properties;

  // @Compoenet DownloadConfigEventHandler
  @Autowired
  private DownloadConfigEventHandler downloadConfigEventHandler;    
  ..
  ..
}

All of these instances will be autowired as expected! Even Spring Events with the Publisher is working as expected as in https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2.


MockMvc standalone setup is for unit testing. You are doing integration testing when you are creating Spring context in test. Don't mix these two types of testing.

So just change it this way:

@SpringApplicationConfiguration(classes = ApplicationAndConfiguration.class)
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class TestController {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() throws Exception {
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }