[java] Spring @ContextConfiguration how to put the right location for the xml

In our project we are writting a test to check if the controller returns the right modelview

@Test
    public void controllerReturnsModelToOverzichtpage()
    {
        ModelAndView modelView = new ModelAndView();
        KlasoverzichtController controller = new KlasoverzichtController();
        modelView = controller.showOverzicht();

        assertEquals("Klasoverzichtcontroller returns the wrong view ", modelView.getViewName(), "overzicht");
    }

This returns the exception null.

We are now configuring the @contextconfiguration but we don't know how to load the right xml who is located at src\main\webapp\root\WEB-INF\root-context.xml

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TestOverzichtSenario{
....

This documentation isn't clear enough to understand

Any suggestion on how to make sure the contextannotation loads the right xml?

Edit v2

I copied the configuration .xml files from the webINF folder to

src\main\resources\be\..a bunch of folders..\configuration\*.xml 

and changed the web.xml in webinf to

<param-name>contextConfigLocation</param-name>
<param-value>
            classpath*:configuration/root-context.xml
            classpath*:configuration/applicationContext-security.xml
        </param-value>

and now get the error

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
    org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
    org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    javax.servlet.GenericServlet.init(GenericServlet.java:212)
    com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:80)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:379)
    java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

This question is related to java unit-testing spring annotations maven

The answer is


We Use:

@ContextConfiguration(locations="file:WebContent/WEB-INF/spitterMVC-servlet.xml")

the project is a eclipse dynamic web project, then the path is:

{project name}/WebContent/WEB-INF/spitterMVC-servlet.xml

Our Tests look like this (using Maven and Spring 3.1):

@ContextConfiguration
(
  {
   "classpath:beans.xml",
   "file:src/main/webapp/WEB-INF/spring/applicationContext.xml",
   "file:src/main/webapp/WEB-INF/spring/dispatcher-data-servlet.xml",
   "file:src/main/webapp/WEB-INF/spring/dispatcher-servlet.xml"
  }
)
@RunWith(SpringJUnit4ClassRunner.class)
public class CCustomerCtrlTest
{
  @Resource private ApplicationContext m_oApplicationContext;
  @Autowired private RequestMappingHandlerAdapter m_oHandlerAdapter;
  @Autowired private RequestMappingHandlerMapping m_oHandlerMapping;
  private MockHttpServletRequest m_oRequest;
  private MockHttpServletResponse m_oResp;
  private CCustomerCtrl m_oCtrl;

// more code ....
}

Simple solution is

@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml" })

from spring forum


Sometimes it might be something pretty simple like missing your resource file in test-classses folder due to some cleanups.


This is a maven specific problem I think. Maven does not copy the files form /src/main/resources to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.

An easier way is to instead put a test specific context definition in the /src/test/resources directory and load via:

@ContextConfiguration(locations = { "classpath:mycontext.xml" })

Suppose you are going to create a test-context.xml which is independent from app-context.xml for testing, put test-context.xml under /src/test/resources. In the test class, have the @ContextConfiguration annotation on top of the class definition.

@ContextConfiguration(locations = "/test-context.xml")
public class MyTests {
    ...
}

Spring document Context management


@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/Beans.xml"}) public class DemoTest{}


Loading the file from: {project}/src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml" })     
@WebAppConfiguration
public class TestClass {
    @Test
    public void test() {
         // test definition here..          
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to unit-testing

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 How to test the type of a thrown exception in Jest Unit Tests not discovered in Visual Studio 2017 Class Not Found: Empty Test Suite in IntelliJ Angular 2 Unit Tests: Cannot find name 'describe' Enzyme - How to access and set <input> value? Mocking HttpClient in unit tests Example of Mockito's argumentCaptor How to write unit testing for Angular / TypeScript for private methods with Jasmine Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to annotations

How to inject a Map using the @Value Spring Annotation? intellij incorrectly saying no beans of type found for autowired repository @Autowired - No qualifying bean of type found for dependency Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll Can't find @Nullable inside javax.annotation.* Name attribute in @Entity and @Table Get rid of "The value for annotation attribute must be a constant expression" message @Value annotation type casting to Integer from String What does -> mean in Python function definitions? @Nullable annotation usage

Examples related to maven

Maven dependencies are failing with a 501 error Why am I getting Unknown error in line 1 of pom.xml? Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Unable to compile simple Java 10 / Java 11 project with Maven ERROR Source option 1.5 is no longer supported. Use 1.6 or later 'react-scripts' is not recognized as an internal or external command How to create a Java / Maven project that works in Visual Studio Code? "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException