web-dev-qa-db-fra.com

Spring @ContextConfiguration comment mettre le bon emplacement pour le xml

Dans notre projet, nous écrivons un test pour vérifier si le contrôleur renvoie la bonne vue de modèle

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

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

Cela retourne l'exception null.

Nous sommes en train de configurer la @contextconfiguration mais nous ne savons pas charger le bon XML qui se trouve dans src\main\webapp\root\WEB-INF\root-context.xml

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

Cette documentation n'est pas assez claire pour comprendre

Toute suggestion sur la façon de vous assurer que la contextannotation charge le bon fichier XML?

Edit v2

J'ai copié les fichiers de configuration .xml du dossier webINF dans 

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

et changé le web.xml dans webinf en 

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

et maintenant obtenir l'erreur 

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)
46
David

C'est la raison pour laquelle ne pas mettre la configuration dans webapp.

Autant que je sache, il n’existe aucun moyen d’accéder aux fichiers du dossier webapp à partir des tests unitaires. Vous pouvez mettre votre configuration dans src/main/resources à la place, afin de pouvoir y accéder à partir de vos tests unitaires (comme décrit dans la documentation), ainsi que de la webapp (en utilisant le préfixe classpath: dans contextConfigLocation).

Voir également:

39
axtavt

Nos tests ressemblent à ceci (avec Maven et 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 ....
}
69
bernd

C’est un problème spécifique aux hommes, je pense. Maven ne copie pas les fichiers de /src/main/resources dans le dossier cible-test. Vous devrez le faire vous-même en configurant le plugin de ressources, si vous voulez absolument aller dans cette direction.

Une méthode plus simple consiste à placer une définition de contexte spécifique au test dans le répertoire /src/test/resources et à la charger via:

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

La solution simple est 

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

de forum de printemps

10
Bala

Nous utilisons:

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

le projet est un projet Web dynamique Eclipse, le chemin est le suivant:

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

Supposons que vous créiez un fichier test-context.xml indépendant de app-context.xml pour le test, placez test-context.xml sous/src/test/resources. Dans la classe de test, placez l'annotation @ContextConfiguration au-dessus de la définition de la classe.

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

Document de printemps Gestion du contexte

4
Dino Tw

Chargement du fichier à partir de: {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..          
    }
}
3
Arpit

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

0
Deepu Surendran