Unit Testing for XML Context

Learn how to write a unit test that uses the XML configuration.

We'll cover the following

The @ContextConfiguration annotation is used to load Java as well as XML context. We created an XML application context file for the MovieRecommenderSystemApplication. Following is the XML configuration file:

<beans xmlns="http://www.springframework.org/schema/beans"

    <context:component-scan base-package=
             "io.datajek.spring.basics.movierecommendersystem.lesson14" use-default-filters="false">
    <!-- enable detection of @Autowired annotation -->
    <bean id="filter" 
    <bean id="filter2" 
    <bean id="recommenderImpl" class=


In this file, we have mentioned the package for component scanning using the <context:component-scan> tag. We have also defined three beans: filter, filter2, and recommenderImpl.

@ContextConfiguration with locations

  1. We will create a test called RecommenderImplementationXmlConfigTest in src/test/java/ for testing the RecommenderImplementation class. When using Java context, the @ContextConfiguration annotation took classes as an argument. To load the XML configuration, we will provide locations as an argument. Since the config file is in the class path, the location can be given as follows:


    The above line will load the file appContext.xml that contains the definition of beans and their dependencies.

  2. The rest of the test will remain the same as done using the Java context:

    class RecommenderImplementationXmlConfigTest {
        private RecommenderImplementation recommenderImpl;
        void testRecommendMovies() {
            assertArrayEquals(new String[] {"Happy Feet", "Ice Age", "Shark Tale"}, 
                                    recommenderImpl.recommendMovies("Finding Dory"));

Get hands-on with 1000+ tech skills courses.

Learn to code, grow your skills, and succeed in your tech interview