Announcement Announcement Module
No announcement yet.
InitialContext using AbstractTransactionalSpringContextTests Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • InitialContext using AbstractTransactionalSpringContextTests


    I'm running Spring unit tests by subclassing AbstractTransactionalSpringContextTests. Some of my classes attempt to read environment properties from the web.xml, using

    context = new javax.naming.InitialContext();

    In the unit tests, that context cannot be initialised, error message is

    Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

    I'd really like to access my web.xml directly, without injecting property values (copy/paste from web.xml) into an environment object. How can I load the web.xml (or even just the env-entry nodes). Using Tomcat for deployment.

    Thanks a lot

    btw: I've found quite a few posts describing the exact problem, but no solution. I've come across the MockServletContext, but am not sure if that relates to the issue or not.

  • #2
    Added a call to the following method in my unit test constructor:

    protected void createNamingContext() {
    		SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
    		try {
    			TypeConverter converter = new SimpleTypeConverter();
    			XPath xpath = XPathFactory.newInstance().newXPath();
    			Document webxmlDom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(WEB_XML_PATH));
    			NodeList enventries = (NodeList)xpath.evaluate("/web-app/env-entry", webxmlDom, XPathConstants.NODESET);
    			for (int n = 0; n < enventries.getLength(); n++) {
    				Node enventry = enventries.item(n);
    				String entryName = (String)xpath.evaluate("env-entry-name", enventry, XPathConstants.STRING);
    				String entryValue = (String)xpath.evaluate("env-entry-value", enventry, XPathConstants.STRING);
    				String entryType = (String)xpath.evaluate("env-entry-type", enventry, XPathConstants.STRING);
    				logger.debug("Loading " + entryName + " into the naming context");
    				Class type = Class.forName(entryType);
    				builder.bind("java:comp/env/" + entryName, converter.convertIfNecessary(entryValue, type));
    		} catch (Exception e) {
    			logger.fatal(e.getMessage(), e);
    			System.setProperty(Context.INITIAL_CONTEXT_FACTORY, AbstractSpringTestCase.class.getPackage().getName() + ".MockInitialContextFactory");
    I'm still sure I've just re-invented the wheel, but ...