a peek into my MIND

February 8, 2010

Exiting nested loops in java using named statements

Filed under: Java — Bharat Kondeti @ 10:17 pm

There may be cases when one has to break the outer for loop when a condition get’s satisfied in the inner for loop.

In the following example code, I am finding the country where the state belongs to..

Country rc = null;
boolean stop = false;
for (Country country : countries) {
	if(stop) break;
	for (State state : country.getStates()) {
		if(state.getName().equalsIgnoreCase(stateName)) {
			rc = country; stop = true; break;
		}
	}
}

In the following example I am naming my external for loop and passing that name to the break statement.

Country rc = null;
COUNTRY:
for (Country country : countries) {
	for (State state : country.getStates()) {
		if(state.getName().equalsIgnoreCase(stateName)) {
			rc = country; break COUNTRY;
		}
	}
}
Advertisements

February 4, 2010

Unit testing iBATIS SqlMapClient with EasyMock

Filed under: Java, Testing — Bharat Kondeti @ 3:44 pm

Integrating iBATIS to an application using spring framework is pretty straight forward. Testing a DAO code with live database will make it an integration test.

In general I write two kinds of tests for any DAO code

  • Unit Test – Using EasyMock to mock a DataSource, SqlMapSession and SqlMapClient.
  • Integration test – Using DBUnit to create and delete the db data.

Following is an example DAO code. We are using iBATIS with spring. Code can be much more complex with multiple calls to database and can have some logic inside it.

import java.util.List;

import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class SomeDAODBImpl extends SqlMapClientDaoSupport {
	
  public List<Customer> lookupCustomers(String zip) {
    List<Customer> customerList = null;
    try {
      SqlMapClientTemplate template = getSqlMapClientTemplate();
      customerList = template.queryForList("Some-Ibatis-Statement-Name", zip);
    } catch (Exception ex) {
       //TODO: Do something with the caught exception
    }
    return customerList;
  }
}

To unit test this code one have to create a mock datasource, session and client. Following is an example unit test code.

(more…)

Create a free website or blog at WordPress.com.