Announcement Announcement Module
Collapse
No announcement yet.
Injection problem trying to do a test with JUnit Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Injection problem trying to do a test with JUnit

    Hello,
    I do not know if this is the right section of the forum for this topic, if is it not the right one, could you fill in at the best place to ask?

    For a university project I have develop a simple MVC application that implements a DAO used to insert and take some data in and from a MySql database.

    I have to make a simple test for this DAO using JUnit, so I have created in my NetBeans project a test package in the "Test Packages" folder, and in this package I have created a JUnit class for the test named: "PoiDaoTest" and I have implemented a simple test in this class but when I try to run this class I receive an error message.

    The code of PoiDaoTest class is:

    Code:
    package test;
    
    import dao.PoiDao;
    import domain.POI;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import org.springframework.test.AbstractTransactionalSpringContextTests;
    
    public class PoiDaoTest extends AbstractTransactionalSpringContextTests {
    
        private PoiDao toTest;     // Dichiaro una variabile di tipo PoiDao generico
        private List <POI> pois;         // array di Poi
        private POI poi;
    
        protected String[] getConfigLocation() {
            return new String[]{
                "file:web/WEB-INF/applicationContext.xml",
                "file:web/WEB-INF/dispatcher-servlet.xml"
            };
        }
    
        @Override
        public void onSetUp() throws Exception {
            toTest = (PoiDao)getApplicationContext().getBean("poiDao");
            pois = new ArrayList<POI>();
    
            for(int i=0; i<=10; i++){
                poi = new POI();
    
                poi.setNome("Poi " + i);
                poi.setLon(i);
                poi.setLat(i);
                poi.setAlt(i);
                poi.setTipologia(0);
                poi.setWikiLink("Poi Wiki: " + i);
    
                pois.add(poi);
                toTest.insert(poi);
            }      
            
        }
    
        @Override
        public void onTearDown() throws Exception {
    
        }
    
        public void testGetRangePoi() {
           List<HashMap> temp = toTest.getRangePoi(2, 2, 1);
           assertTrue("La lista contiene pi di un elemento: ",temp.size()==1);
    
           HashMap punto = temp.get(0);
           Float tempLong = (Float)punto.get("long");
           Float tempLat = (Float)punto.get("lat");
    
           boolean bool = tempLong.equals(new Float(2)) && tempLat.equals(new Float(2));
           assertTrue("Il punto trovato non  quello atteso: ",bool);
        }
    
    }
    The object PoiDao toTest is the DAO object that I would to test
    The POI object is an object that rappresent a Point Of Interest with some field (name, description, longitude, latitude, etcetc), and pois is a list of POI object.

    In my code I have implement the getConfigLocation() method and I have put the path of my 2 XML configuration file (I think that the path is correct).

    Then I have override the onSetup() Spring test method in which I obtain the poiDao bean that have to be test and in wich I create a list contenent 10 new POI object.

    The testGetRangePoi() implements the specific test that I would to do...

    The problem is that if I try to execute the class that implements the test give me this error message:

    Code:
    ------------- Standard Error -----------------
    13-nov-2010 0.20.49 org.springframework.test.AbstractDependencyInjectionSpringContextTests prepareTestInstance
    INFO: ApplicationContext has not been configured for test [test.PoiDaoTest]: dependency injection will NOT be performed.
    ------------- ---------------- ---------------
    Testcase: testGetRangePoi(test.PoiDaoTest):        Caused an ERROR
    null
    java.lang.NullPointerException
            at test.PoiDaoTest.onSetUp(PoiDaoTest.java:35)
            at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:104)
            at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:79)
    
    
    Test test.PoiDaoTest FAILED
    /home/andrea/NetBeansProjects/InsertPoi/nbproject/build-impl.xml:957: Some tests failed; see details above.
    BUILD FAILED (total time: 2 seconds)
    Do you have some idea about it? How can I solve this problem?

    Thanks
    Andrea

  • #2
    Hi,

    is there any particular reason why you're not using JUnit 4?

    Which version of Spring are you using ? If you're using latest Spring release (3.0.5) I suggest you switch to JUnit 4 and use org.springframework.test.context.junit4.AbstractJU nit4SpringContextTests.

    Comment


    • #3
      Originally posted by Enrico Pizzi View Post
      Hi,

      is there any particular reason why you're not using JUnit 4?

      Which version of Spring are you using ? If you're using latest Spring release (3.0.5) I suggest you switch to JUnit 4 and use org.springframework.test.context.junit4.AbstractJU nit4SpringContextTests.
      no, there is no particular reason for using JUnit 3.05.
      Where do you see that I'm not using JUnit 4? I do not read the version used in the posted error message.

      Anyway...could you explain me in detail what should I do?
      I use NetBeans and in "Test Libraries" path I have two JAR file named: junit-3.8.2.jar and jumint-4.5.jar and in the libraries path I use Spring Framework 3.0.2 RELEASE

      What I have to do to switch to the last version of Junit in my project?

      what could be causing that error? I compensator that may be because you can not inject the context when calling the method getConfigLocation(), is it possible?

      Code:
      protected String[] getConfigLocation() {
              return new String[]{
                  "file:web/WEB-INF/applicationContext.xml",
                  "file:web/WEB-INF/dispatcher-servlet.xml"
              };
          }

      Thank you very much
      Andrea

      Comment


      • #4
        Where do you see that I'm not using JUnit 4?
        JUnit 4 is annotation-driven. Also, you're extending AbstractTransactionalSpringContextTests and not AbstractJUnit4SpringContextTests.

        I have two JAR file named: junit-3.8.2.jar and junit-4.5.jar
        This is wrong. You should never have 2 versions of the same jar on your classpath, it causes classcastexception issues 99% of the time, and it is probably contributing as a cause to your error.
        I suggest you use Maven to manage your project dependencies (it's the easiest and safest way).
        If you want to do it by hand, remove junit 3 jar from your lib dir and also check that your container doesn't have its own version in its shared libraries folder.
        Also, after you have done this, do a full redeploy of the application by deleting it and checking inside the server temp folders that the jar has been effectively deleted (sometimes containers like tomcat or weblogic aren't smart enough to do it properly).
        I also suggest you use junit 4.8 and not 4.5, so delete also this jar, download the 4.8 version and copy it to the lib folder (or just use Maven and specify the version in your project's pom).

        What I have to do to switch to the last version of Junit in my project?
        Once you have removed 3.8 and 4.5 and installed 4.8, all you have to do is write a test class like this one (you can create a junit 4 test case from eclipse, then modify it to add spring framework functionality, take special notice of the bold parts):

        Code:
        package gesic.dao.tests;
        
        import java.sql.SQLException;
        import java.text.SimpleDateFormat;
        import java.util.List;
        
        import enelit.classibase.schema.Ritorno;
        import gesic.dao.MessaggioSSGDao;
        import gesic.pojos.FiltroMessaggiSSGPOJO;
        import gesic.pojos.ListaMessaggiSSGPOJO;
        import gesic.pojos.MessaggioSSGPOJO;
        import gesic.pojos.RiepilogoMessaggioSSGPOJO;
        
        import org.junit.Assert;
        
        import org.junit.After;
        import org.junit.Before;
        import org.junit.Test;
        import org.springframework.test.context.ContextConfiguration;
        import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
        
        @ContextConfiguration(locations = {"file:/C:/SVN/RilasciWLS10/wls/GESIW/WebContent/WEB-INF/spring-test.xml"})
        public class MessaggioSSGDaoTest extends AbstractJUnit4SpringContextTests {
        	
        	private MessaggioSSGDao dao;
        	private FiltroMessaggiSSGPOJO filtro;
        	private Number idmessaggio;
        	private String cdutente;
        	private Number idunita;
        	private MessaggioSSGPOJO messaggio;
        
        	@Before
        	public void setUp() throws Exception {
        		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        		dao = (MessaggioSSGDao) applicationContext.getBean("messaggioSSGDaoImpl");
        		filtro = new FiltroMessaggiSSGPOJO();
        		filtro.setIdunitavismsg(223359);
        		filtro.setDtinserimentoDa(sdf.parse("13/10/2010"));
        		idmessaggio = 11004;
        		cdutente = "ssgvebs1";
        		idunita = 223359;
        		messaggio = new MessaggioSSGPOJO();
        		messaggio.setOreduratamessaggio(2);
        		messaggio.setTpdispacc("E");
        		messaggio.setTestomessaggio("Junit test per inserimento messaggio ssg su wls10 - spring");
        		messaggio.setCdutente("ssgvebs1");
        		messaggio.setIdunitains(223359);
        	}
        
        	@After
        	public void tearDown() throws Exception {
        		
        		dao = null;
        		filtro = null;
        		idmessaggio = null;
        		cdutente = null;
        		idunita = null;
        	}
        
        	@Test
        	public void testCaricaListaMessaggiSSG() {
        		try {
        			List<ListaMessaggiSSGPOJO> result = dao.caricaListaMessaggiSSG(filtro);
        			Assert.assertNotNull("La lista e' null", result);
        			Assert.assertTrue("La lista e' vuota", result.size() != 0);
        			System.out.println("N. elementi trovati: " + result.size());
        		} catch (SQLException ex) {
        			Assert.fail(ex.getMessage());
        		}
        	}
        
        	@Test
        	public void testCessaMessaggioSSG() {
        		try {
        			Ritorno result = dao.cessaMessaggioSSG(idmessaggio, cdutente);
        			Assert.assertTrue("L'operazione non e' andata a buon fine", result.getMajorCode() == 0);
        		} catch (SQLException ex) {
        			Assert.fail(ex.getMessage());
        		}
        	}
        
        	@Test
        	public void testDettaglioMessaggioSSG() {
        		try {
        			MessaggioSSGPOJO result = dao.dettaglioMessaggioSSG(idmessaggio);
        			Assert.assertNotNull("l'oggetto ritornato e' null", result);
        			System.out.println(result);
        			Assert.assertTrue("", result.getTpdispacc().equals("E"));
        		} catch (SQLException ex) {
        			Assert.fail(ex.getMessage());
        		}
        	}
        
        	@Test
        	public void testEliminaMessaggioSSG() {
        		try {
        			Ritorno result = dao.eliminaMessaggioSSG(idmessaggio);
        			Assert.assertTrue("L'operazione non e' andata a buon fine", result.getMajorCode() == 0);
        		} catch (SQLException ex) {
        			Assert.fail(ex.getMessage());
        		}
        	}
        
        	@Test
        	public void testRiepilogoMessaggioSSG() {
        		try {
        			RiepilogoMessaggioSSGPOJO result = dao.riepilogoMessaggioSSG(idmessaggio, idunita);
        			Assert.assertNotNull("L'oggetto ritornato e' null", result);
        			System.out.println(result);
        		} catch (SQLException ex) {
        			Assert.fail(ex.getMessage());
        		}
        	}
        
        	@Test
        	public void testSalvaMessaggioSSG() {
        		try {
        			Ritorno result = dao.salvaMessaggioSSG(messaggio);
        			System.out.println("majorcode: " + result.getMajorCode() + ", majormsg: " + result.getMajorMsg() + 
        				", minorcode: " + result.getMinorCode() + ", minormsg: " + result.getMinorMsg());
        			Assert.assertTrue("L'operazione non e' andata a buon fine", result.getMajorCode() == 0);
        		} catch (SQLException ex) {
        			Assert.fail(ex.getMessage());
        		}
        	}
        
        }

        Comment


        • #5
          Thanks for the reply but I still have some problems to run my test.

          I have not used Maven in this project because I do not know and now I have to finish just by entering this test. It seems to me a very useful tool in the next project I will definitely use it but for now I prefer to handle it by hand

          I did the following operation:

          1) I have delete the 2 old JUnit libraries from the Test Libraries folder of my NetBeans project and I have and I replaced with the file named: Junit-4.8.2.jar dowloaded from JUnit official website.

          2) I have take your code and I have modified it to create a first minimal test (only useful to see if it run), this is the code:

          Code:
          package test;
          
          import dao.PoiDao;
          import domain.POI;
          
          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.List;
          
          import org.junit.After;
          import org.junit.Before;
          import org.junit.Test;
          import org.springframework.test.context.ContextConfiguration;
          import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
          
          @ContextConfiguration(locations = {"file:/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/applicationContext.xml"})
          public class PoiDaoTest extends AbstractJUnit4SpringContextTests {
          
          	private PoiDao daoToTest;           // Dichiaro una variabile di tipo PoiDao generico
                  private List <POI> pois;         // array di Poi
                  private POI poi1;                 // Rappresenta un generico oggetto di tipo POI
          
                  /* Cose da fare prima che inizzi il test vero e proprio */
          	@Before
          	public void setUp() throws Exception {
          
                      // Inietta il bean poiDao ?!?!
                      daoToTest = (PoiDao)applicationContext.getBean("poiDao");
          
                       poi1 = new POI();         // crea un nuovo oggetto POI
          
                       // Setta i valori dei campi dell'oggetto POI appena creato
                       poi1.setNome("TEST 1");
                       poi1.setLon(5);
                       poi1.setLat(5);
                       poi1.setAlt(5);
                       poi1.setTipologia(1);
                       poi1.setWikiLink("WIKI LINK TEST 1");
                       System.out.println("Ho creato il seguente oggetto POI: " + poi1.getNome() + " " + poi1.getLat() + " " + poi1.getLon());
          
          	}
          
                  /* Cose che vengono fatte dopo il test vero e proprio per ripristinare
                   * la situazione iniziale del sistema come se il test non fosse mai
                     stato fatto */
          	@After
          	public void tearDown() throws Exception {
          		daoToTest = null;       // Resetta a null il riferimento al dao da testare
                          System.out.println("Il test  terminato !!!");
          	}
          
                  /* Testa l'inserimento di un singolo punto di interesse nel DB utilizzando
                   * il DAO */
          	@Test
          	public void testInsertPoi() {
                      daoToTest.insert(poi1);     // Salva l'oggetto poi1 nel DB
                      System.out.println("Ho inserito il POI nel DB");
          	}	
          
          }
          It is very simple: in the setUp() method I inject my DAO bean and I create a new POI object setting the value of its field.
          In the testInsertPoi() method I would test that the POI object is put in the DB and at this time I would only save the object in the DB calling the DAO.

          But I have some problem because give me some errors...
          Maybe the error might be because in my project I have two XML configuration files and when I refer only to the XML file to the main line:
          @ContextConfiguration(locations = {"file:/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/applicationContext.xml"})

          and I have also an other bean configuration file named dispatcher-servlet.xml in my project !!!

          Comment


          • #6
            If I open NetBeans and I run the test file I get the following error messages:

            ERROR 1:

            Code:
            ------------- Standard Error -----------------
            15-nov-2010 21.49.02 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
            INFO: Loading XML bean definitions from URL [file:/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/applicationContext.xml]
            15-nov-2010 21.49.02 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
            INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
            15-nov-2010 21.49.02 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
            INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
            15-nov-2010 21.49.02 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
            INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
            15-nov-2010 21.49.02 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
            INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
            15-nov-2010 21.49.02 org.springframework.context.support.AbstractApplicationContext prepareRefresh
            INFO: Refreshing [email protected]b60c3: startup date [Mon Nov 15 21:49:02 CET 2010]; root of context hierarchy
            15-nov-2010 21.49.02 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
            INFO: Loading properties file from class path resource [WEB-INF/jdbc.properties]
            15-nov-2010 21.49.02 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
            INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5d3e754f: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,savedService,propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,poiService,poiDao]; root of factory hierarchy
            15-nov-2010 21.49.02 org.springframework.test.context.TestContextManager prepareTestInstance
            GRAVE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@48fd918a] to prepare test instance [test.PoiDaoTest@7f5e2075]
            java.lang.IllegalStateException: Failed to load ApplicationContext
                    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
                    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
                    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
                    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)
                    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
                    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
                    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
                    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
                    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
                    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
                    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
                    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
                    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
                    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
                    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
                    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
                    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
                    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
                    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
                    at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
                    at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
                    at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
                    at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
            Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/jdbc.properties] cannot be opened because it does not exist
                    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:78)
                    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:640)
                    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:615)
                    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:405)
                    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
                    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
                    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
                    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
                    ... 22 more
            Caused by: java.io.FileNotFoundException: class path resource [WEB-INF/jdbc.properties] cannot be opened because it does not exist
                    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
                    at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
                    at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:161)
                    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:69)
                    ... 29 more
            ------------- ---------------- ---------------

            Comment


            • #7
              ERROR 2:

              Code:
              Testcase: testInsertPoi(test.PoiDaoTest):        Caused an ERROR
              Failed to load ApplicationContext
              java.lang.IllegalStateException: Failed to load ApplicationContext
                      at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
                      at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
                      at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
                      at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
                      at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
                      at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
              Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/jdbc.properties] cannot be opened because it does not exist
                      at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:78)
                      at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:640)
                      at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:615)
                      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:405)
                      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
                      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
                      at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
                      at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
              Caused by: java.io.FileNotFoundException: class path resource [WEB-INF/jdbc.properties] cannot be opened because it does not exist
                      at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
                      at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
                      at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:161)
                      at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:69)
              
              
                      at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
                      at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
                      at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
                      at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
                      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
                      at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
                      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
                      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
                      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
                      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
                      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
                      at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
                      at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
                      at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
                      at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
                      at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
                      at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
                      at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
              Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/jdbc.properties] cannot be opened because it does not exist
                      at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:78)
                      at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:640)
                      at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:615)
                      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:405)
                      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
                      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
                      at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
                      at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
                      ... 22 more
              Caused by: java.io.FileNotFoundException: class path resource [WEB-INF/jdbc.properties] cannot be opened because it does not exist
                      at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
                      at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
                      at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:161)
                      at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:69)
                      ... 29 more
              Test test.PoiDaoTest FAILED
              /home/andrea/NetBeansProjects/InsertPoi/nbproject/build-impl.xml:957: Some tests failed; see details above.
              BUILD FAILED (total time: 3 seconds)

              Comment


              • #8
                If you have more than one xml config file defining your test application context, you should specify both of them in the locations attribute of the @ContextConfiguration annotation, like this:

                Code:
                @ContextConfiguration(locations = {"file:/mypath/file1.xml", "file:/mypath/file2.xml"})
                The {} are there because the locations attribute accepts an array of strings, so that you can load all your files.

                The error you are having seems related to this, so try again specifying both files, if it doesn't work post the new error and we'll look into it.

                Comment


                • #9
                  Originally posted by Enrico Pizzi View Post
                  If you have more than one xml config file defining your test application context, you should specify both of them in the locations attribute of the @ContextConfiguration annotation, like this:

                  Code:
                  @ContextConfiguration(locations = {"file:/mypath/file1.xml", "file:/mypath/file2.xml"})
                  The {} are there because the locations attribute accepts an array of strings, so that you can load all your files.

                  The error you are having seems related to this, so try again specifying both files, if it doesn't work post the new error and we'll look into it.
                  Ok, I tried to do as you told me seguendte making the change:

                  Code:
                  @ContextConfiguration(locations = {"file:/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/applicationContext.xml", "/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet.xml"})
                  So now I have included my 2 XML file...

                  Now if I run the test file give me this error message:

                  Code:
                  WARNING: multiple versions of ant detected in path for junit 
                           jar:file:/home/andrea/netbeans-6.9/java/ant/lib/ant.jar!/org/apache/tools/ant/Project.class
                       and jar:file:/home/andrea/glassfish-3.0.1/glassfish/modules/ant.jar!/org/apache/tools/ant/Project.class
                  Testsuite: test.PoiDaoTest
                  16-nov-2010 11.53.42 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
                  INFO: Loading XML bean definitions from URL [file:/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/applicationContext.xml]
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
                  INFO: Loading XML bean definitions from class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet.xml]
                  16-nov-2010 11.53.42 org.springframework.test.context.TestContextManager prepareTestInstance
                  GRAVE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6833f0de] to prepare test instance [test.PoiDaoTest@2a0ab444]
                  java.lang.IllegalStateException: Failed to load ApplicationContext
                  Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0,864 sec
                  
                  ------------- Standard Error -----------------
                  16-nov-2010 11.53.42 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
                  INFO: Loading XML bean definitions from URL [file:/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/applicationContext.xml]
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                  INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
                  16-nov-2010 11.53.42 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
                  INFO: Loading XML bean definitions from class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet.xml]
                  16-nov-2010 11.53.42 org.springframework.test.context.TestContextManager prepareTestInstance
                  GRAVE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6833f0de] to prepare test instance [test.PoiDaoTest@2a0ab444]
                  java.lang.IllegalStateException: Failed to load ApplicationContext
                  Seem that it load something but give an error because:
                  Code:
                  GRAVE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6833f0de] to prepare test instance [test.PoiDaoTest@2a0ab444]
                  java.lang.IllegalStateException: Failed to load ApplicationContext
                  Do you have some idea? :-(

                  Thanks
                  Andrea

                  Comment


                  • #10
                    There is a configuration error in the second file you are trying to load, dispatcher-servlet.xml.
                    My guess is that this file contains web-application specific configuration, which won't load outside a web-specific container (WebXmlApplicationContext) for the context. Remember that AbstractJUnit4SpringContextTests loads the application context as a ClasspathXmlApplicationContext.

                    My question is: do you really need to load web specific configuration to do your tests? If you are testing daos, services etc. you shouldn't need to load the servlet-specific file. If you're testing something web-specific like a controller, then you should create a copy of your dispatcher-servlet.xml and rename it to dispatcher-servlet-test.xml, then remove from this file all the stuff that isn't necessary for your test. Then reference this new file in the locations attribute.

                    To find out what the error really is, you should activate log4j logging at debug level for the Spring framework, so that you will get more specific information.

                    I also suggest that you fix the ant.jar duplicate problem that is showed as a warning at the beginning of your log.

                    Comment


                    • #11
                      Originally posted by Enrico Pizzi View Post
                      There is a configuration error in the second file you are trying to load, dispatcher-servlet.xml.
                      My guess is that this file contains web-application specific configuration, which won't load outside a web-specific container (WebXmlApplicationContext) for the context. Remember that AbstractJUnit4SpringContextTests loads the application context as a ClasspathXmlApplicationContext.

                      My question is: do you really need to load web specific configuration to do your tests? If you are testing daos, services etc. you shouldn't need to load the servlet-specific file. If you're testing something web-specific like a controller, then you should create a copy of your dispatcher-servlet.xml and rename it to dispatcher-servlet-test.xml, then remove from this file all the stuff that isn't necessary for your test. Then reference this new file in the locations attribute.

                      To find out what the error really is, you should activate log4j logging at debug level for the Spring framework, so that you will get more specific information.

                      I also suggest that you fix the ant.jar duplicate problem that is showed as a warning at the beginning of your log.
                      I am a true principainte with Java and Spring...Roughly I think I understand but I have some doubt about it:

                      1) Exactly what you mean when you say: AbstractJUnit4SpringContextTests loads the application context as a ClasspathXmlApplicationContext

                      2) In fact it is a web application and as you say I have to test only the DAO, so probabily I don't need to load the servlet-specific file of the web application so I will try to remove from this file all the stuff that isn't necessary for your test...but are you sure that the problem is only in my dispatcher-servlet.xml file and not also in the applicationContext.xml file?

                      3) What is log4j ? I do not know this tool...

                      So...my original dispatcher-servlet.xml file is it:

                      Code:
                      <?xml version="1.0" encoding="UTF-8"?>
                      <beans xmlns="http://www.springframework.org/schema/beans"
                             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                             xmlns:p="http://www.springframework.org/schema/p"
                             xmlns:aop="http://www.springframework.org/schema/aop"
                             xmlns:tx="http://www.springframework.org/schema/tx"
                             xmlns:context="http://www.springframework.org/schema/context"
                             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
                      
                          <context:annotation-config />
                      
                          <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
                          
                          <!--
                          Most controllers will use the ControllerClassNameHandlerMapping above, but
                          for the index controller we are using ParameterizableViewController, so we must
                          define an explicit mapping for it.
                          -->
                          <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
                              <property name="mappings">
                                  <props>
                                      <prop key="index.htm">indexController</prop>
                                  </props>
                              </property>
                          </bean>
                          
                          <bean id="viewResolver"
                                class="org.springframework.web.servlet.view.InternalResourceViewResolver"
                                p:prefix="/WEB-INF/jsp/"
                                p:suffix=".jsp" />
                          
                          <!--
                          The index controller.
                          -->
                          <bean name="indexController"
                                class="org.springframework.web.servlet.mvc.ParameterizableViewController"
                                p:viewName="index" />
                      
                      
                          <bean class="controller.InsertpoiController" 
                                p:savedService-ref="savedService"
                                p:poiService-ref="poiService"
                                p:validator-ref="poiValidator"/>
                      
                          <bean  id="poiValidator" class="domain.PoiValidator" />
                      
                          <bean  id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />
                      
                          <context:component-scan base-package="controller" /> 
                          
                      </beans>
                      Since now I would test only the DAO I have create a new file named dispatcher-serlet-test.xml within which I have deleted all the code that does not concern the DAO...so I have:

                      Code:
                      <?xml version="1.0" encoding="UTF-8"?>
                      <beans xmlns="http://www.springframework.org/schema/beans"
                             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                             xmlns:p="http://www.springframework.org/schema/p"
                             xmlns:aop="http://www.springframework.org/schema/aop"
                             xmlns:tx="http://www.springframework.org/schema/tx"
                             xmlns:context="http://www.springframework.org/schema/context"
                             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
                      
                          <context:annotation-config />
                      
                      </beans>
                      And I have changed the @ContextConfiguration value in the test file...but I have this error message

                      Comment


                      • #12
                        1) ERROR 1:
                        Code:
                        ------------- Standard Error -----------------
                        16-nov-2010 16.31.50 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
                        INFO: Loading XML bean definitions from URL [file:/home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/applicationContext.xml]
                        16-nov-2010 16.31.51 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                        INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
                        16-nov-2010 16.31.51 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                        INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
                        16-nov-2010 16.31.51 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                        INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
                        16-nov-2010 16.31.51 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
                        INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
                        16-nov-2010 16.31.51 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
                        INFO: Loading XML bean definitions from class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml]
                        16-nov-2010 16.31.51 org.springframework.test.context.TestContextManager prepareTestInstance
                        GRAVE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5090d8ea] to prepare test instance [test.PoiDaoTest@559113f8]
                        java.lang.IllegalStateException: Failed to load ApplicationContext
                                at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
                                at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
                                at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
                                at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)
                                at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
                                at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
                                at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
                                at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
                                at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
                                at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
                                at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
                                at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
                                at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
                                at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
                                at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
                                at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
                                at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
                                at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
                                at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
                                at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
                                at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
                                at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
                                at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
                        Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml]; nested exception is java.io.FileNotFoundException: class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml] cannot be opened because it does not exist
                                at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
                                at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
                                at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
                                at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
                                at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
                                at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
                                at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:81)
                                at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
                                at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
                                at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
                                ... 22 more
                        Caused by: java.io.FileNotFoundException: class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml] cannot be opened because it does not exist
                                at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
                                at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
                                ... 31 more
                        Some ideas? :-(

                        Comment


                        • #13
                          2) ERROR 2:
                          Code:
                          ------------- ---------------- ---------------
                          Testcase: testInsertPoi(test.PoiDaoTest):        Caused an ERROR
                          Failed to load ApplicationContext
                          java.lang.IllegalStateException: Failed to load ApplicationContext
                                  at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
                                  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
                                  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
                                  at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
                                  at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
                                  at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
                          Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml]; nested exception is java.io.FileNotFoundException: class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml] cannot be opened because it does not exist
                                  at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
                                  at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
                                  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:81)
                                  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
                                  at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
                                  at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
                          Caused by: java.io.FileNotFoundException: class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml] cannot be opened because it does not exist
                                  at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
                                  at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
                          
                          
                                  at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
                                  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
                                  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
                                  at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
                                  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
                                  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
                                  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
                                  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
                                  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
                                  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
                                  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
                                  at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
                                  at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
                                  at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
                                  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
                                  at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
                                  at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
                                  at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
                                  at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
                          Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml]; nested exception is java.io.FileNotFoundException: class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml] cannot be opened because it does not exist
                                  at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
                                  at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
                                  at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
                                  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:81)
                                  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
                                  at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
                                  at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
                                  ... 22 more
                          Caused by: java.io.FileNotFoundException: class path resource [home/andrea/NetBeansProjects/InsertPoi/web/WEB-INF/dispatcher-servlet-test.xml] cannot be opened because it does not exist
                                  at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
                                  at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
                                  ... 31 more
                          Test test.PoiDaoTest FAILED
                          /home/andrea/NetBeansProjects/InsertPoi/nbproject/build-impl.xml:957: Some tests failed; see details above.
                          BUILD FAILED (total time: 4 seconds)

                          Comment


                          • #14
                            If you're testing a dao, you don't need to load the servlet xml, so just load the other one (the one that registers (or scans for) your dao). Add only that to the locations attribute.
                            Then you can delete the test file you created, it's useless and only adds to the confusion.

                            You really need to activate log4j to see what the error is when loading just the applicationContext.xml file, you probably won't see much otherwise.

                            Problem is I can't instruct you on log4j right now, just download it and learn how to configure it, you'll need it anyway sooner or later.

                            Comment

                            Working...
                            X