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"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package=
"io.datajek.spring.basics.movierecommendersystem.lesson14" use-default-filters="false">
</context:component-scan>
<!-- enable detection of @Autowired annotation -->
<context:annotation-config/>
<bean id="filter"
class="io.datajek.spring.basics.movierecommendersystem.lesson14.ContentBasedFilter"/>
<bean id="filter2"
class="io.datajek.spring.basics.movierecommendersystem.lesson14.CollaborativeFilter"/>
<bean id="recommenderImpl" class=
"io.datajek.spring.basics.movierecommendersystem.lesson14.RecommenderImplementation"/>
</beans>
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
-
We will create a test called
RecommenderImplementationXmlConfigTest
in src/test/java/ for testing theRecommenderImplementation
class. When using Java context, the@ContextConfiguration
annotation tookclasses
as an argument. To load the XML configuration, we will providelocations
as an argument. Since the config file is in the class path, the location can be given as follows:@ContextConfiguration(locations="/appContext.xml")
The above line will load the file appContext.xml that contains the definition of beans and their dependencies.
-
The rest of the test will remain the same as done using the Java context:
@ExtendWith(SpringExtension.class) @ContextConfiguration(locations="/appContext.xml") class RecommenderImplementationXmlConfigTest { @Autowired private RecommenderImplementation recommenderImpl; @Test 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