How to Create A Java Class Performance Test Using JMeters AbstractJavaSamplerClient

JMeter is a very powerfull tools to do performance testing. In this tutorial, im going to simulate a heavy load on a java object to test its strength and performance testing. My java class is very simple, only an ordinary java class to do inserts into mysql database using Hibernate framework.

first is a sample database and a table

CREATE DATABASE test;
USE test;
CREATE
    TABLE student
    (
        id INT NOT NULL AUTO_INCREMENT,
        studentname VARCHAR(60) NOT NULL,
        PRIMARY KEY (id)
    );

a java class and xml as representation for database’s table

package com.edw.bean;

public class Student implements java.io.Serializable {

    private Integer id;
    private String studentname;

    public Student() {
    }

    public Student(String studentname) {
       this.studentname = studentname;
    }
	
	// other setter and getter
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.edw.bean.Student" table="student" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="studentname" type="string">
            <column name="studentname" length="60" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

this is my Hibernate main configuration xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">xxxxxx</property>
    <property name="hibernate.connection.autocommit">true</property>
    <mapping resource="com/edw/bean/Student.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

and my java class to load Hibernate’s configuration

package com.edw.hbm;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * @author edw
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {            
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

This is my tested java class, it has to extends AbstractJavaSamplerClient so the jmeter application can test it

package com.edw.test;

import com.edw.bean.Student;
import com.edw.hbm.HibernateUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *  com.edw.test.StudentStressTest
 *
 *  @author edw
 */
public class StudentStressTest extends AbstractJavaSamplerClient {

    private Map<String, String> mapParams = new HashMap<String, String>();
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public StudentStressTest() {
        super();
    }

    @Override
    public void setupTest(JavaSamplerContext context) {
        for (Iterator<String> it = context.getParameterNamesIterator(); it.hasNext();) {
            String paramName =  it.next();
            mapParams.put(paramName, context.getParameter(paramName));
        }
    }

    public SampleResult runTest(JavaSamplerContext context) {
        SampleResult result = new SampleResult();

        try {

            JMeterVariables vars = JMeterContextService.getContext().getVariables();
            vars.put("demo", "demoVariableContent");

            result.sampleStart();

            Student student = new Student();
            student.setStudentname(mapParams.get("name")+" "+new Date().getTime());
            Session session = sessionFactory.openSession();
            session.save(student);
            session.flush();
            session.close();

            result.sampleEnd();

            
            result.setSuccessful(true);
            result.setSampleLabel("SUCCESS: " + student.getStudentname());

        } catch (Throwable e) {
            result.sampleEnd();
            result.setSampleLabel("FAILED: '" + e.getMessage() + "' || " + e.toString());
            result.setSuccessful(false);

            e.printStackTrace();
            System.out.println("\n\n\n");
        }

        return result;
    }

    @Override
    public Arguments getDefaultParameters() {

        Arguments params = new Arguments();

        params.addArgument("name", "edw");

        return params;
    }
}

Next is build your project into jar and put it into jmeter’s path ( \lib\ext ), dont forget to copy your application library such as hibernate3.jar.
If you open your JMeter ui, you can see your java class on Add > Sampler > Java Request. You can see the results sumamry on tab summary report.

This is my Netbeans project structure, and my jmeter configuration.

Have fun working with JMeter :)

Google+

2 Comments

Samir

about 3 years ago

Does this example really generates meaningful report ? I followed similar approch for my EJB component stress testing!!! Though test casses executing however no data in report !!!!! CAN U PLS TELL ME ABOUT Sleep_time AND Sleep_mask ?

Reply

edwin

about 3 years ago

hi Samir, you can generate report using one of jmeter's component, using "Summary_Report"

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)