ERROR LazyInitializationException:42 – failed to lazily initialize a collection of role no session or session was closed org.hibernate.LazyInitializationException


Discount: https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=spring32coupon

19 aug 2015 10:03:24,448 ERROR LazyInitializationException:42 – failed to lazily initialize a collection of role: class, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: class, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)

Solution on JUnit tests

@Test
@Transactional

And @Entity level use fetch = FetchType.EAGER

@OneToMany(mappedBy = "groups", fetch = FetchType.EAGER)
Advertisements

java.lang.Exception: No runnable methods at org.junit.runners.BlockJUnit4ClassRunner


Discount: https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=spring32coupon

Solution
use @Test on JUnit methods

java.lang.Exception: No runnable methods
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:171)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:115)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:269)
at org.junit.runners.ParentRunner.(ParentRunner.java:66)
at org.junit.runners.BlockJUnit4ClassRunner.(BlockJUnit4ClassRunner.java:59)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:104)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

JUnit test TestGoogleGeocoding



package test.nl.kameroom.location;

import java.io.InputStream;
import java.io.StringReader;
import java.net.URI;
import java.net.URL;
import java.sql.SQLException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.InputSource;


public class TestGoogleGeocoding {
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testGeocoding() throws Exception {			
		    
		URI uri = new URI(
			    "http", 
			    "maps.googleapis.com",
			    "/maps/api/geocode/xml",
			    "address=,+NL&sensor=false", 
			    null);
		URL url = uri.toURL();
		InputStream is = url.openStream();
		String xml = IOUtils.toString(is, "utf-8"); //encoding is important
      
		XPathFactory xpathFactory = XPathFactory.newInstance();
		XPath xpath = xpathFactory.newXPath();
		System.out.println(xml);
		String lng = xpath.evaluate("//GeocodeResponse/result/geometry/location/lng[1]", new InputSource(new StringReader(xml)));
		String lat = xpath.evaluate("//GeocodeResponse/result/geometry/location/lat[1]", new InputSource(new StringReader(xml)));
		System.out.println("lng=" + lng);
		System.out.println("lat=" + lat);
		is.close(); 
	}
	
}


How to use JUnit for testing Java Classes (Simple Example)


First download latest JUnit jar and put it into project's lib folder

Create a SimpleCalculator.java class like the following one;

package junitexampleproject;

/**
*
* @author tunatore
*/
public class SimpleCalculator {

public int addTwoNumber(int a, int b) {
return a+b;
}
public int minusTwoNumber(int a, int b) {
return a-b;
}
public int multipyNumber(int a, int b) {
return a*b;
}
public int divideNumber(int a, int b) {
return a/b;
}

}

Second create a JUnit test class; SimpleCalculatorTest .java

package junitexampleproject;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
*
* @author tunat
*/
public class SimpleCalculatorTest {

public SimpleCalculatorTest() {
}

@BeforeClass
public static void setUpClass() throws Exception {
//System.out.println(“1:setUpClass() is executing…”);
}

@AfterClass
public static void tearDownClass() throws Exception {
//System.out.println(“4:tearDownClass() is executing…”);
}

@Before
public void setUp() {
//System.out.println(“2:setUp() is executing…”);
}

@After
public void tearDown() {
//System.out.println(“3:tearDown() is executing…”);
}

/**
* Test of addTwoNumber method, of class SimpleCalculator.
*/
@Test
public void testAddTwoNumber() {
System.out.println(“addTwoNumber”);
int a = 2;
int b = 2;
SimpleCalculator instance = new SimpleCalculator();
int expResult = 4;
int result = instance.addTwoNumber(a, b);
assertEquals(expResult, result);
}

/**
* Test of minusTwoNumber method, of class SimpleCalculator.
*/
@Test
public void testMinusTwoNumber() {
System.out.println(“minusTwoNumber”);
int a = 140;
int b = 40;
SimpleCalculator instance = new SimpleCalculator();
int expResult = 100;
int result = instance.minusTwoNumber(a, b);
assertEquals(expResult, result);
}

/**
* Test of multipyNumber method, of class SimpleCalculator.
*/
@Test
public void testMultipyNumber() {
System.out.println(“multipyNumber”);
int a = 220;
int b = 2;
SimpleCalculator instance = new SimpleCalculator();
int expResult = 440;
int result = instance.multipyNumber(a, b);
assertEquals(expResult, result);
}

/**
* Test of divideNumber method, of class SimpleCalculator.
*/
@Test
public void testDivideNumber() {
System.out.println(“divideNumber”);
int a = 90;
int b = 45;
SimpleCalculator instance = new SimpleCalculator();
int expResult = 2;
int result = instance.divideNumber(a, b);
assertEquals(expResult, result);
}

}

After running  unit test by calling it from IDE such as NetBeans

Result will be shown as in green color meaning that all tests are successful or will be shown as red meaning some of the tests or all of them are failed.

Sample screen

Second example;

Create an Employee.java class such as the following one;

package junitexampleproject;

/**
*
* @author tunatore
*/
public class Employee {

// manager will be ‘M’
// employee will be ‘E’
// others will be ‘O’

private char type;

public Employee(char type) {
this.type = type;
}

/**
* @return the type
*/
public char getType() {
return type;
}

/**
* @param type the type to set
*/
public void setType(char type) {
this.type = type;
}

}

Create a SalaryCalculator.java class for getting minimum salary for employees

package junitexampleproject;

/**
*
* @author tunatore
*/
public class SalaryCalculator {

public int getSalary(Employee e) {

switch(e.getType()) {
case ‘E’:
//employee will get 2000$
return 2000;
case ‘M’:
//manager will get 3000$
return 3000;
default:
//others will get 1000$
return 1000;
}

}
}

And last create a test class for SalaryCalculator.java class –> SalaryCalculatorTest.java

package junitexampleproject;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
*
* @author tunatore
*/
public class SalaryCalculatorTest {

public SalaryCalculatorTest() {
}

@BeforeClass
public static void setUpClass() throws Exception {
//System.out.println(“1:setUpClass() is executing…”);
}

@AfterClass
public static void tearDownClass() throws Exception {
//System.out.println(“4:tearDownClass() is executing…”);
}

@Before
public void setUp() {
//System.out.println(“2:setUp() is executing…”);
}

@After
public void tearDown() {
//System.out.println(“3:tearDown() is executing…”);
}

/**
* Test of calculateSalary method, of class SalaryCalculator.
*/
@Test
public void testCalculateSalary() {

System.out.println(“calculateSalary”);
SalaryCalculator instance = new SalaryCalculator();

Employee manager = new Employee(‘M’);
int managerSalary = instance.getSalary(manager);
assertTrue(managerSalary >= 3000);

Employee employee = new Employee(‘E’);
int employeeSalary = instance.getSalary(employee);
assertTrue(employeeSalary >= 2000);

//if you comment out the following lines
//unit test will fail
//because others salaries can not be greater than 1000 $
//it must be
/*

Employee others = new Employee(‘0’);
int othersSalary = instance.getSalary(others);
assertTrue(othersSalary >= 1500);

*/

}

}

After executing this result will be;

Sample Screen

//if you comment out the following lines
//unit test will fail
//because others salaries can not be greater than 1000 $
//it must be
/*

Employee others = new Employee(‘0’);
int othersSalary = instance.getSalary(others);
assertTrue(othersSalary >= 1500);

*/

Lets comment out the lines defined above and execute tests again;

Download Sample NetBeans Project

Some Useful assert methods taken from JUnit doc
assertArrayEquals(java.lang.Object[] expecteds, java.lang.Object[] actuals)
assertEquals(java.lang.Object expected, java.lang.Object actual)
assertFalse(boolean condition)
assertNotNull(java.lang.Object object)
assertNotNull(java.lang.String message, java.lang.Object object)
assertNotSame(java.lang.Object unexpected, java.lang.Object actual)
assertNull(java.lang.Object object)
assertTrue(boolean condition)
fail(java.lang.String message)