• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 297
  • Last Modified:

A method to start a hibernate object.

I have built a logging method around TestSuites in junit.

It works great for TestSuites, however, if I try to run a single test case, I lose my logging ability. I need to break my logging up so I can call it for a test suite, or a single test case. Any support is greatly appreciated:

this is one test suite:

/*
 * Created on May 6, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.apc.qa.ate.test.http;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;

import junit.framework.TestFailure;
import junit.framework.TestResult;
import junit.framework.TestSuite;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;

import org.apache.log4j.Logger;

import com.apc.qa.ate.Result;
import com.apc.qa.ate.Summary;
import com.apc.qa.ate.dao._RootDAO;
import com.apc.qa.ate.util.Util;

/**
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 *
 * @author marcadam
 **/
public class AllHttpTests extends TestSuite {
    /**
     * Logger for this class
     */
    private static final Logger atelog = Logger.getLogger(AllHttpTests.class);
   
    static Map resultMap = new HashMap();
    static Summary summary = null;
   
    protected TestSuite getTestSuite() {
       
        TestSuite suite;
        suite = new TestSuite("AllHttpUnitTests");
        suite.addTestSuite(DeviceIdentification.class);
        return suite;
    }
       
    /**
     * Runs all the test classes specified in the TestSuite.
     * Gets the TestSuite to run, then runs the tests and finally
     * displays the results.
     */
    public void runAllTests() {
        Summary p = new Summary();
        try {
            _RootDAO.initialize();
            SessionFactory sessionFactory = new Configuration().configure()
            .buildSessionFactory();
            Session session = sessionFactory.openSession();
            p.setResult(new HashSet());
            p.setCategory("Configuration");
            p.setFirmware(Util.getFirmwareApp());
            p.setInterface("http");
            p.setPowernetMib(Util.getMib());
            java.util.Date now = new java.util.Date();
            p.setTestDate(new java.sql.Timestamp(now.getTime()));
            p.setSsh(Util.getSsh());
            p.setSl(Util.getSsl());
            p.setTester(System.getProperty("user.name"));
            summary = p;
            TestResult results = new TestResult();
            TestSuite suite = getTestSuite();
            runTestSuite(suite, results);
            displayResults(results, p);
            getResultHash(p);
            session.save(p);
            session.flush();
            session.close();
        } catch (HibernateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
   
    /**
     * Runs the test suite
     * @param TestResults results: all results are placed within this object
     * @param TestSuite suite: the suite of tests to run
     */
    protected void runTestSuite(TestSuite suite, TestResult results) {
        suite.run(results);
    }
   
    /**
     * Prints out the status of the results (successful/unsuccessful).
     * If there are errors or failures more detailed error messages are
     * printed giving the stack trace.
     * @param TestResults results: the results to use.
     */
    protected void displayResults(TestResult results, Summary p) {
        atelog.info("Ran " + results.runCount() + " tests");
        p.setTestRun(results.runCount());
        if(results.wasSuccessful()) {
            p.setTestPassed(results.runCount());
            atelog.info("All tests successful");
        }
        else {
            // failures occur when the fail method is invoked within a
            // test method
            atelog.info(results.failureCount() + " Failures");
            p.setTestFailed(results.failureCount());
            p.setTestPassed(results.runCount() - results.failureCount());
            for (Enumeration e = results.failures() ; e.hasMoreElements() ;) {
                atelog.info(e.nextElement());
            }
           
            // errors happen when the test method throws an exception
            // you can get the initial Throwable and interrogate it to
            // retrieve the stack trace
            atelog.info(results.errorCount() + " Errors");
            for (Enumeration e = results.errors() ; e.hasMoreElements() ;) {
                TestFailure failure = (TestFailure) e.nextElement();
                atelog.info(failure);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(baos);
                Throwable t = failure.thrownException();
                t.printStackTrace(ps);
                atelog.info(baos);
            }
        }
    }    
   
   
    public static void getResultHash(Summary p) {
        Iterator it = resultMap.values().iterator();
        while (it.hasNext()) {
            // Get value
            Result value = (Result)it.next();
            p.getResult().add(value);
            value.setSummary(p);
        }
    }
   
    /**
     * @return Returns the summary.
     */
    public static Summary getSummary() {
        return summary;
    }
    /**
     * @param summary The summary to set.
     */
    public static void setSummary(Summary summary) {
        summary = AllHttpTests.summary;
    }
   
    /**
     * @return Returns the resultMap.
     */
    public static Map getResultMap() {
        return resultMap;
    }
    /**
     * @param resultMap The resultMap to set.
     */
    public void setResultMap(Map resultMap) {
        AllHttpTests.resultMap = resultMap;
    }
}


The resultMap is a hash of results built in the test case class.

Essentially, I need the hibernate call to build summary and save and close the session in separate method(s). So that the code:

            TestResult results = new TestResult();
            TestSuite suite = getTestSuite();
            runTestSuite(suite, results);
            displayResults(results, p);
            getResultHash(p);

can be run inside the hibernate creation, or the test case can be run via:

(newtestCaseClass("Test Name")).run();

and have the hibernate code wrapped around it......

I hope this is explained alright.
0
k41d3n
Asked:
k41d3n
  • 4
  • 2
1 Solution
 
aozarovCommented:
Create and configure Hibernate session in some other (utility and not part of the tests) class and provide static
access to it. The utility will create Configuration and a factory only once (store in static variables)
The utility will have a method to get Hibernate Session.
The session will be used the module[s] responsible to dump the data.
0
 
aozarovCommented:
>> The session will be used the module[s] responsible to dump the data.
The session will be used by module[s] responsible to dump the data. (e.g. by displayResults or by the test tearDown)
0
 
mightyoneCommented:
you don'seem to have configured your logger right...


try using setLevvel(ALL);

and make sure to give it a valid property file

use. eg  -Djava.util.logging.config.file=xxxx.props
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
aozarovCommented:
mightyone, he is using log4j "org.apache.log4j.Logger;"
0
 
mightyoneCommented:
so then use  -D org.apache.log4j.config.file=file://xxxx.props
0
 
aozarovCommented:
I think its actually calld log4.configuration (but I don't think it is his problem)
0
 
k41d3nAuthor Commented:
The logging is fine, it uses log4j.properties

Thanks again aozarov, I used your idea and created a hibernate object that contains all the hibernate information I need.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now