0

I have configured MysqlDataSource in tomcat using this link.I have written junit test cases.when am i calling below connection from junit it throws following errors.

javax.naming.NoInitialContextException: 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 have used following code

class DataConnection {
    private static DataSource dataSource;

public DataConnection() {
    try {
        Context ctx = new InitialContext();
        dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/test");
    } catch (NamingException e) {
       e.printStackTrace(); 
    }
}

public static Connection getConnection() throws SQLException {
    new DataConnection();
      Connection con=dataSource.getConnection();
      return con;
}
}

How to call tomcat from junit? How to achieve this?

Community
  • 1
  • 1
Ami
  • 4,241
  • 6
  • 41
  • 75
  • Have you considered writing a small Shell or Windows batch script to invoke the Tomcat container? Your JUnit code could just invoke this script in the `setUp()`. – asgs Mar 11 '13 at 07:43
  • 1
    Could be a possible duplicate of [how-to-start-and-stop-an-tomcat-container-with-java](http://stackoverflow.com/questions/2190300/how-to-start-and-stop-an-tomcat-container-with-java) – asgs Mar 11 '13 at 07:52

2 Answers2

0

The code you give gets the database connection from JNDI, e.g. when running in tomcat from the container. However, for Unit Tests (assuming that's what you use JUnit for) I'd rather suggest to use "dependency injection" - e.g. explicitly pass a database connection to the code under test or manually set it up before the test runs.

There's no need to rely on JNDI for executing your tests: That's not what you want to test, instead, you want to just verify that your actual code is running correctly.

You don't need any fancy library (e.g. spring) for dependency injection, just a slightly adjusted architecture. This will greatly enhance the testability of your application and lower the execution time of your tests.

(This is based on my assumptions of your situation based on the little bit of information that you give in your question)

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
0

Give TomcatJNDI a try. It is based on embedded Tomcat but initializes only Tomcat's JNDI environment without starting a server. So you can access all your resources as configured in Tomcat's configuration files in tests or from within any Java SE application. The API is simple. For instance to get a DataSource declared in context.xml:

TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processContextXml(contextXmlFile);
tomcatJNDI.start();

Then you can lookup the DataSource as usual

DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/path/to/datasource")

More information about TomcatJNDI can be found here.

Holger Thurow
  • 764
  • 4
  • 12