Skip to content

@WebMvcTest and @WebAppConfiguration behave differently with ServletContext resources #16484

@lorenzodee

Description

@lorenzodee

I'm porting a Spring app to Spring Boot 2.0.x and observed a different behavior with ServletContext resources.

Here's the non-boot test, and works as expected.

@WebAppConfiguration
@RunWith(SpringRunner.class)
public class SampleNonBootTest {

	@EnableWebMvc
	@Configuration
	static class TilesConfig {
		@Bean
		public TilesConfigurer tilesConfigurer() {
			TilesConfigurer tilesConfigurer = new TilesConfigurer();
			tilesConfigurer.setDefinitions("/WEB-INF/views/tiles.xml");
			tilesConfigurer.setCheckRefresh(true);
			return tilesConfigurer;
		}

		// @Bean
		// tilesViewResolver not relevant for this issue
	}
	
	@Autowired
	private WebApplicationContext context;

	private MockMvc mockMvc;

	@Before
	public void setUp() throws Exception {
		mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void test() throws Exception {
		mockMvc.perform(get("/"))
			.andExpect(status().isNotFound());
	}

}

And here's the boot test, but fails to load ApplicationContext due to a missing resource WEB-INF/views/tiles.xml. But the non-boot test succeeds, and the file exists.

@WebMvcTest
@RunWith(SpringRunner.class)
public class SampleBootTest {
	
	@Autowired
	private MockMvc mockMvc;

	@TestConfiguration
	static class TilesConfig {
		@Bean
		public TilesConfigurer tilesConfigurer() {
			TilesConfigurer tilesConfigurer = new TilesConfigurer();
			tilesConfigurer.setDefinitions("/WEB-INF/views/tiles.xml");
			tilesConfigurer.setCheckRefresh(true);
			return tilesConfigurer;
		}

		// @Bean
		// tilesViewResolver not relevant for this issue
	}

	@Before
	public void setUp() throws Exception {
		// Failed to load ApplicationContext
		// No URL for ServletContext resource [/WEB-INF/views/tiles.xml]
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void test() throws Exception {
		mockMvc.perform(get("/"))
			.andExpect(status().isNotFound());
	}

}

I've also tried loading an existing resource using an @Autowired ServletContext. It too fails when using @WebMvcTest. I don't think it has anything to do with Apache Tiles. But I've used it as an example here, since that is how I encountered the different behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: supersededAn issue that has been superseded by another

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions