Master the most popular testing framework for Java, through the Learn JUnit course:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
The hybrid definition of beans in a Spring Boot application is one that includes both an Annotation-Based and XML-Based configuration. In this environment, we may want to use the XML-Based configuration in the test classes. However, sometimes in this situation, we may encounter the application context loading error βFailed to load ApplicationContext.β This error appears in the test classes because the application context isnβt loaded in the test context.
In this tutorial, weβll discuss how to integrate the XML application context into testing in a Spring Boot application.
Further reading:
Testing in Spring Boot
Integration Testing in Spring
Spring Boot Error ApplicationContextException
2. βFailed to load ApplicationContextβ Error
Letβs reproduce the error by integrating the XML-Based application context in a Spring Boot application.
First, letβs suppose we have an application-context.xml file with the definition of a service bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeServiceImpl" class="com.baeldung.xmlapplicationcontext.service.EmployeeServiceImpl" />
</beans>
Now we can add the application-context.xml file in the webapp/WEB-INF/ location:
π ApplicationContextDirecoryWeβll also create a service interface and class:
public interface EmployeeService {
Employee getEmployee();
}
public class EmployeeServiceImpl implements EmployeeService {
@Override
public Employee getEmployee() {
return new Employee("Baeldung", "Admin");
}
}
Finally, weβll create a test case for getting the EmployeeService bean from the application context:
@RunWith(SpringRunner.class)
@ContextConfiguration(locations={"classpath:WEB-INF/application-context.xml"})
public class EmployeeServiceAppContextIntegrationTest {
@Autowired
private EmployeeService service;
@Test
public void whenContextLoads_thenServiceISNotNull() {
assertThat(service).isNotNull();
}
}
Now if we try to run this test, weβll observe the error:
java.lang.IllegalStateException: Failed to load ApplicationContext
This error appears in the test classes because the application context isnβt loaded in the test context. Moreover, the root cause is that the WEB-INF isnβt included in the classpath:
@ContextConfiguration(locations={"classpath:WEB-INF/application-context.xml"})
3. Using an XML-Based ApplicationContext in Test
Letβs see how we can use an XML-Based ApplicationContext in test classes. We have two options to use the XML-Based ApplicationContext in the test: @SpringBootTest and @ContextConfiguration annotations.
3.1. Test Using @SpringBootTest and @ImportResource
Spring Boot provides the @SpringBootTest annotation, which we can use to create an application context to be used in a test. In addition, we must use @ImportResource in the Spring Boot main class for reading XML beans. This annotation allows us to import one or more resources containing bean definitions.
First, letβs use the @ImportResource annotation in the main class:
@SpringBootApplication
@ImportResource({"classpath*:application-context.xml"})
Now letβs create a test case for getting EmployeeService bean from the application context:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = XmlBeanApplication.class)
public class EmployeeServiceAppContextIntegrationTest {
@Autowired
private EmployeeService service;
@Test
public void whenContextLoads_thenServiceISNotNull() {
assertThat(service).isNotNull();
}
}
The @ImportResource annotation loads XML beans located in the resource directory. In addition, the @SpringBootTest annotation loads the whole applicationβs beans in the test class. Therefore, weβre able to access the EmployeeService bean in the test class.
3.2. Test Using @ContextConfiguration With resources
We can create our test context with different configurations of beans by placing our test configuration file in the src/test/resources directory.
In this case, we use the @ContextConfiguration annotation for loading the test context from the src/test/resources directory.
First, letβs create another bean from the EmployeeService interface:
public class EmployeeServiceTestImpl implements EmployeeService {
@Override
public Employee getEmployee() {
return new Employee("Baeldung-Test", "Admin");
}
}
Then weβll create the test-context.xml file in the src/test/resources directory:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeServiceTestImpl" class="process.service.EmployeeServiceTestImpl" />
</beans>
Finally, weβll create the test case:
@SpringBootTest
@ContextConfiguration(locations = "/test-context.xml")
public class EmployeeServiceTestContextIntegrationTest {
@Autowired
@Qualifier("employeeServiceTestImpl")
private EmployeeService serviceTest;
@Test
public void whenTestContextLoads_thenServiceTestISNotNull() {
assertThat(serviceTest).isNotNull();
}
}
Here we loaded employeeServiceTestImpl from the test-context.xml using the @ContextConfiguration annotation.
3.3. Test Using @ContextConfiguration With WEB-INF
We can also import an application context in the test classes from the WEB-INF directory. To do this, we can address the application context using its file URL:
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/application-context.xml")
4. Conclusion
In this article, we learned how to use XML-Based configuration files in test classes in a Spring Boot application.
