<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>REVERT TO CONSOLE &#187; UnitTest</title>
	<atom:link href="http://www.reverttoconsole.com/blog/category/unittest/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.reverttoconsole.com</link>
	<description>for f in *;do echo &#124; sed &#039;i\rtc&#039; &#62;&#62; $f;done; java programming et al</description>
	<lastBuildDate>Thu, 25 Aug 2011 15:02:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Mock Unit Testing Services and Daos with Mockito and Spring 3</title>
		<link>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/#comments</comments>
		<pubDate>Mon, 09 May 2011 14:46:02 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=984</guid>
		<description><![CDATA[If you haven&#8217;t been mocking yet, check this out. There are other tools in Groovy using DSLs but if you want to stick to Java, Mockito is by far the best BDD-style mock unit testing tool. Traditional examples provide a List mocking example or foo/bar example which I find it mostly annoying since it doesn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t been <em>mocking </em>yet, check <a href="http://www.mockito.org/">this </a>out. There are other tools in Groovy using DSLs but if you want to stick to Java, Mockito is by far the best BDD-style mock unit testing tool.  </p>
<p>Traditional examples provide a List mocking example or foo/bar example which I find it mostly annoying since it doesn&#8217;t teach you how to solve real problems. And the documentation is verbose and crams with unnecessary features confusing us further. In this tutorial, I&#8217;ll dive straight into a relevant example of mock testing Daos in Service layer. I&#8217;m not a big fan of Daos anymore (after the advent of JPA), however for the purposes of this tutorial, it&#8217;ll be easier to explain.</p>
<p>Consider a Profile entity (like facebook user profile) with daos/services: ProfileDao/JPAProfileDao, ProfileService/ProfileServiceImpl. To complicate things further, say you are using DTOs since it&#8217;s a client server app with a GWT front end. You might need a simple mapper class. Let&#8217;s call it ProfileMapper/ProfileMapperImpl. </p>
<pre>
@Service("profileService")
public class ProfileServiceImpl implements ProfileService {
	private final ProfileDao profileDao;
	private final ProfileMapper profileMapper;

	@Inject
	public ProfileServiceImpl(final ProfileDao profileDao, final ProfileMapper profileMapper) {
		this.profileDao = profileDao;
		this.profileMapper = profileMapper;
	}

	@Transactional
	public void create(ProfileDto profile) throws DuplicateProfileException {
		if (profile == null) {
			throw new IllegalArgumentException("profile cannot be null.");
		}

		Profile profile = profileMapper.toEntity(profile);
		// set default state as active
		profile .setIsActive(true);

		try {
			profileDao.save(profile);
		}
		catch (DuplicateKeyException e) {
			logger.warn("Unable to save profile with userId: " + profile.getUserId() + " already exists.");
			throw new DuplicateProfileException();
		}
		logger.debug("Profile saved successfully.");
	}

	@Transactional(readOnly = true)
	public ProfileDto read(String userId) throws InvalidProfileException {
		validateProfileInfo(userId);

		ProfileDto profileDto = null;
		Profile profile = profileDao.read(userId);
		if (profile != null) {
			profileDto = profileMapper.fromEntity(profile);
			logger.debug("Profile retrieved successfully.");
		}
		else {
			logger.debug("...");
		}
		return profileDto;
	}

	...
}
</pre>
<p>Now, in order to test ProfileService, you need to mock out ProfileMapper and ProfileDao, right? Let&#8217;s see how we do this in a simple JUnit 4.4+ test.</p>
<pre>
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ProfileServiceTest {

	@Mock
	ProfileDao profileDao;

	@Mock
	ProfileMapper profileMapper;

	// Can't use @InjectMocks because Mockito doesn't support constructor injection
	// As a workaround use @Before below to initialize service with stubs
	ProfileService profileService;

	@Before
	public void init() {
		profileService = new ProfileServiceImpl(profileDao, profileMapper);
	}

	@Test
	public void testRead() throws InvalidProfileException {
		// Simulate InvalidProfileException
		try {
			profileService.read("");
			fail(); // should never execute
		}
		catch (InvalidProfileException e) {
			e.getMessage(); // expected
		}

		// Given
		Profile profile = TestData.createTestProfile("userid"); // test utility to create a test Profile
		when(profileDao.read("userid")).thenReturn(profile);
		when(profileMapper.fromEntity(profile )).thenReturn(TestData.createTestProfileDto("userid"));

		// When
		ProfileDto dto = profileService.read("userid");

		// Then
		assertEquals(dto.getUserId(), "userid");
	}
}
</pre>
<p>Explanation:<br />
1) Wrapping your test with @RunWith(MockitoJUnitRunner.class) helps create the mock initialization through annotation scanning (@Mock, @InjectMocks)<br />
2) Add @Mock annotations for the components to mock. In this case profileDao, profileMapper<br />
3) As of 1.8.5, Mockito doesn&#8217;t provide @InjectMock with construction injection. @Before test initializer is a workaround to inject ProfileService with mocks. Note that this will not be required if ProfileService has setter/getter injection of dependencies. However, I prefer JSR330 construction injection which is a <a href="http://martinfowler.com/articles/injection.html#ConstructorVersusSetterInjection">best practice </a>.<br />
4) The actual @Test class with mockito stubs. Let&#8217;s dig deep into this.</p>
<p>As a template, it&#8217;s a good practice to view tests like a BDD style test. </p>
<pre>
// Given 

// When

// Then
</pre>
<p>The above template forces you to think on the explicit conditions during which we run our unit test.</p>
<p>Next, we need to figure out a way to stub our mock component&#8217;s methods,</p>
<pre>
when(operation).thenReturn(object)
</pre>
<p>In our example we want to mock profileDao.read(userId). So that translates to</p>
<pre>
when(profileDao.read("userid")).thenReturn(profile);
</pre>
<p>Note that we&#8217;re letting the mocked dao return a profile object that we just created in the previous step. This will be 50% of most of your mocking use cases.</p>
<p>The next common used use case is to simulate exceptions from the mocked classes. Consider a test for create(&#8230;) that simulates the DuplicateProfileException.          </p>
<pre>
@Test
	public void testCreateDuplicate() {
		// Given
		ProfileDto dto = TestData.createTestProfileDto("userid");
		Profile profile = TestData.createTestProfile("userid");
		when(profileMapper.toEntity(dto)).thenReturn(profile);
		doThrow(new DuplicateKeyException("duplicate profile")).when(profileDao).save(profile);

		// When
		try {
			profileService.create(dto);
			assertEquals(1, 2); // should never execute
		}
		// Then
		catch (DuplicateProfileException e) {
			e.getMessage();
		}
	}
</pre>
<p>Notice the line</p>
<pre>
doThrow(new DuplicateKeyException("duplicate profile")).when(profileDao).save(profile);
</pre>
<p>Quite simple, isn&#8217;t it? </p>
<p>If you&#8217;ve read so far, you can succuessfully write mock unit tests for 80% of your use cases. There are other advanced features like finding <a href="http://www.mockito.org/">redundant invocations</a>, spying on objects to simulate partial mocking, most of which I don&#8217;t see implementing for majority of my use cases. </p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Spring Security 3 Unit Testing Example with DbUnit</title>
		<link>http://www.reverttoconsole.com/blog/spring/spring-security-3-unit-testing-example-with-dbunit/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/spring-security-3-unit-testing-example-with-dbunit/#comments</comments>
		<pubDate>Wed, 18 Aug 2010 15:03:09 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=701</guid>
		<description><![CDATA[This tutorial extends on the baseline laid by Spring Security Tutorial maven archetype. I&#8217;ve modified the spring security config file and will be unit testing a simple ProfileService (CRUD) on a Profile entity (User object). The tests include login/logout and spring services security unit testing. application-security.xml &#60;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34;?&#62; &#60;beans:beans xmlns=&#34;http://www.springframework.org/schema/security&#34; xmlns:beans=&#34;http://www.springframework.org/schema/beans&#34; xmlns:xsi=&#34;http://www.w3.org/2001/XMLSchema-instance&#34; xsi:schemaLocation=&#34;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial extends on the baseline laid by Spring Security Tutorial maven <a href="http://mvnrepository.com/artifact/org.springframework.security/spring-security-samples-tutorial/3.0.5.RELEASE">archetype</a>.</p>
<p>I&#8217;ve modified the spring security config file and will be unit testing a simple ProfileService (CRUD) on a Profile entity (User object). The tests include login/logout and spring services security unit testing.</p>
<p>application-security.xml</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;beans:beans
    xmlns=&quot;http://www.springframework.org/schema/security&quot;
    xmlns:beans=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/security

http://www.springframework.org/schema/security/spring-security-3.0.xsd&quot;&gt;

	&lt;global-method-security pre-post-annotations=&quot;enabled&quot;/&gt;

	&lt;http use-expressions=&quot;true&quot;&gt;
		&lt;intercept-url pattern=&quot;/secure/extreme/**&quot; access=&quot;hasRole(&#039;ROLE_SUPERVISOR&#039;)&quot;/&gt;
		&lt;intercept-url pattern=&quot;/secure/**&quot; access=&quot;isAuthenticated()&quot; /&gt;
		&lt;intercept-url pattern=&quot;/**&quot; access=&quot;permitAll&quot; /&gt;
		&lt;form-login /&gt;
		&lt;logout /&gt;
		&lt;remember-me /&gt;

		&lt;!-- Uncomment to limit the number of sessions a user can have --&gt;
		&lt;session-management invalid-session-url=&quot;/timeout.jsp&quot;&gt;
			&lt;concurrency-control max-sessions=&quot;1&quot; error-if-maximum-exceeded=&quot;true&quot; /&gt;
		&lt;/session-management&gt;
	&lt;/http&gt;

	&lt;authentication-manager&gt;
		&lt;authentication-provider&gt;
			&lt;!--  &lt;password-encoder hash=&quot;md5&quot;/&gt; --&gt;
			&lt;user-service&gt;
				&lt;user name=&quot;admin&quot; password=&quot;admin&quot; authorities=&quot;ROLE_ADMIN, ROLE_USER&quot; /&gt;
				&lt;user name=&quot;user&quot; password=&quot;user&quot; authorities=&quot;ROLE_USER&quot; /&gt;
				&lt;user name=&quot;reports&quot; password=&quot;reports&quot; authorities=&quot;ROLE_REPORTS&quot; /&gt;
			&lt;/user-service&gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;	

&lt;/beans:beans&gt;
</pre>
<p>Base DB Unit Test with utils for Spring Security</p>
<pre>
import java.io.FileInputStream;
import java.sql.Connection;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.dbunit.database.*;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.transaction.*;

/**
 * Base Test that wraps a DbUnit style Test case by inserting a sample testdata
 * on startup. Provides necessary functions to login/logout, add roles, etc
 */
public abstract class BaseSecurityTest {

	private static final Logger logger = Logger
			.getLogger(BaseSecurityTest.class);

	Connection con;
	IDatabaseConnection dbUnitCon;
	IDataSet dataSet;

	@Inject
	private DataSource dataSource;

	protected abstract String getTestClassname();

	@BeforeTransaction
	public void beforeTx() throws Exception {
		logger.debug("Opening Db Connection ... ");
		con = DataSourceUtils.getConnection(dataSource);
		dbUnitCon = new DatabaseConnection(con);
		dataSet = getDataSet(getTestClassname());

		DatabaseOperation.CLEAN_INSERT.execute(dbUnitCon, dataSet);
	}

	@AfterTransaction
	public void afterTx() throws Exception {
		logger.debug("Releasing Db Connection ...");
		DataSourceUtils.releaseConnection(con, dataSource);
	}

	protected IDataSet getDataSet(String name) throws Exception {
		return new FlatXmlDataSetBuilder().build(new FileInputStream(
				"src/test/resources/" + name + ".xml"));
	}

	protected void clearContext() {
		SecurityContextHolder.clearContext();
	}

	protected void login(String username, String password) {
		SecurityContextHolder.getContext().setAuthentication(
				new UsernamePasswordAuthenticationToken(username, password));

		logger.debug("User:" + username + " logged in");
	}

	protected String getLoginDetails() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {
			return ((UserDetails)principal).getUsername();
		}
		else {
			return principal.toString();
		}

	}
}
</pre>
<p>ProfileServiceTest</p>
<pre>
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import xxx.Profile;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
		&quot;classpath*:spring/applicationContext-core.xml&quot;,
		&quot;classpath*:spring/applicationContext-mail.xml&quot;,
		&quot;classpath*:spring/applicationContext-security.xml&quot; })
@TransactionConfiguration
@Transactional
public class ProfileServiceTest extends BaseSecurityTest {

	private static final Logger logger = Logger
			.getLogger(ProfileServiceTest.class);

	@Inject
	private ProfileService profileService;

	@Override
	protected String getTestClassname() {
		return &quot;ProfileServiceTest&quot;;
	}

	@Test
	public void testUserLogin() {
		login(&quot;admin&quot;, &quot;admin&quot;);
		String username = getLoginDetails();
		assertEquals(username, &quot;admin&quot;);

		login(&quot;user&quot;, &quot;user&quot;);
		String username2 = getLoginDetails();
		assertEquals(username2, &quot;user&quot;);

		login(&quot;reports&quot;, &quot;reports&quot;);
		String username3 = getLoginDetails();
		assertEquals(username3, &quot;reports&quot;);
	}

	@Test
	public void testRead() {

		// Test with role that has access to the service
		login(&quot;user&quot;, &quot;user&quot;);
		profileService.read(&quot;1&quot;);

		login(&quot;reports&quot;, &quot;reports&quot;);
		profileService.read(&quot;1&quot;);

		// Test with role that doesn&#039;t have access to the service
		login(&quot;admin&quot;, &quot;admin&quot;);
		try {
			profileService.read(&quot;1&quot;);
		}
		catch (AccessDeniedException e) {
			// Expected
			assert(true);
			return;
		}

		// it should not reach here
		assert(false);
	}

	@Test
	public void testFindProfiles() {
		List&lt;Profile&gt; list = profileService.FindProfiles();
		assertEquals(4, list.size());
	}

	@Test
	public void testFindProfileById() {
		List&lt;Profile&gt; list = profileService.findProfileById(&quot;123&quot;);
		assertEquals(1, list.size());
	}

	@Test
	public void testSave() {

		// Test with role that has access to the service
		login(&quot;admin&quot;, &quot;admin&quot;);
		Profile dummy = new Profile();
		profileService.save(dummy);		

		// Test with role that doesn&#039;t have access to the service
		login(&quot;reports&quot;, &quot;reports&quot;);
		try {
			profileService.save(dummy);
		}
		catch (AccessDeniedException e) {
			// Expected
			assert(true);
			return;
		}

		// it should not reach here
		assert(false);
	}
}
</pre>
<p>The Profile Service</p>
<pre>
public interface ProfileService {

	@PreAuthorize(&quot;hasRole(&#039;ROLE_USER&#039;) or hasRole(&#039;ROLE_REPORTS&#039;)&quot;)
	Profile read(String id);

	List&lt;Profile&gt; findProfiles();

	List&lt;Profile&gt; findProfileById(String Id);

	@PreAuthorize(&quot;hasRole(&#039;ROLE_ADMIN&#039;) or hasRole(&#039;ROLE_USER&#039;)&quot;)
	Profile save(Profile account);

	@PreAuthorize(&quot;hasRole(&#039;ROLE_ADMIN&#039;)&quot;)
	void delete();

}
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/spring-security-3-unit-testing-example-with-dbunit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Unit Testing JavaScript with HtmlUnit and Screw.Unit</title>
		<link>http://www.reverttoconsole.com/blog/javascript/unit-testing-javascript-with-htmlunit-and-screwunit/</link>
		<comments>http://www.reverttoconsole.com/blog/javascript/unit-testing-javascript-with-htmlunit-and-screwunit/#comments</comments>
		<pubDate>Fri, 29 May 2009 14:30:44 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/blog/java/unit-testing-javascript-with-htmlunit-and-screwunit/</guid>
		<description><![CDATA[Writing apps with today&#39;s rich client libraries such as Extjs , YUI , and JQuery really shows how much potential is still left in web development. But it takes a lot of code, and the amount of technical debt can get heavy, quickly. Good tests can help reduce this technical debt, and there are a lot of testing [...]]]></description>
			<content:encoded><![CDATA[<p>Writing apps with today&#39;s rich client libraries such as <a href="http://extjs.com/">Extjs</a> , <a href="http://developer.yahoo.com/yui/">YUI</a> , and <a href="http://jquery.com/">JQuery</a> really shows how much potential is still left in web development. But it takes a lot of code, and the amount of <a href="http://en.wikipedia.org/wiki/Technical_debt">technical debt</a> can get heavy, quickly. Good tests can help reduce this technical debt, and there are a lot of testing tools available for the client. Today though, I want to go beyond just using a tool, and talk more about integrating your JavaScript tests into an existing <a href="http://en.wikipedia.org/wiki/Continuous_Integration">Continuous Integration</a> environment. 
<div></div>
<div>I have a confession to make- I hate running tests manually. I&#39;ll write tests when I&#39;m doing new development or bug fixing, but I hate running them after I&#39;ve fixed the bug or implemented the code. That&#39;s why we have CI environments, right? So I don&#39;t have to run the stupid tests each time! There are enough ridiculous rules put in place in corporate work environments today already, I don&#39;t like adding tasks that can be automated into the mix.</div>
<div></div>
<div>Here&#39;s what I&#39;ve come up with for integrating my JavaScript Unit Tests:</div>
<div></div>
<div>
<ol>
<li>Write tests with <a href="http://github.com/nkallen/screw-unit/tree/master">Screw.Unit</a> . Why Screw.Unit? I like the simple DOM it creates. I like the code behind it- specifically the separation of builders and matchers. It&#39;s relatively easy to debug my code in Firebug. But mostly, it&#39;s because it&#39;s of the easy DOM it displays. There&#39;s nothing magical about Screw.Unit. It&#39;s just a simple tool. But that&#39;s the point.</li>
<li>Use <a href="http://htmlunit.sourceforge.net/">HtmlUnit</a> to execute Screw.Unit tests, and inspect the results. HtmlUnit has the best JavaScript framework support in the Java world today. It uses <a href="http://www.mozilla.org/rhino/">Rhino</a> to execute JavaScript and has written very comprehensive DOM support on top of that. It can handle most major JS framework code. So I execute my tests with HtmlUnit, and then inspect the simple DOM results. Easy!</li>
<li>I use a <a href="http://junit.org/apidocs/org/junit/runners/Parameterized.html">Parameterized JunitTest</a> to read through all of my ScrewUnit tests (*.html files), and execute a JUnit test for each. </li>
</ol>
<div>Done! Simple integration at it&#39;s best.</div>
</p></div>
<p style="font-size: 10px;">  <a href="http://posterous.com">Posted via email</a>   </p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F&amp;title=Unit+Testing+JavaScript+with+HtmlUnit+and+Screw.Unit" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F&amp;title=Unit+Testing+JavaScript+with+HtmlUnit+and+Screw.Unit" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F&amp;title=Unit+Testing+JavaScript+with+HtmlUnit+and+Screw.Unit" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F&amp;title=Unit+Testing+JavaScript+with+HtmlUnit+and+Screw.Unit" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F&amp;title=Unit+Testing+JavaScript+with+HtmlUnit+and+Screw.Unit', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F&amp;title=Unit+Testing+JavaScript+with+HtmlUnit+and+Screw.Unit" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjavascript%2Funit-testing-javascript-with-htmlunit-and-screwunit%2F&amp;title=Unit+Testing+JavaScript+with+HtmlUnit+and+Screw.Unit" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/javascript/unit-testing-javascript-with-htmlunit-and-screwunit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails and HtmlUnit</title>
		<link>http://www.reverttoconsole.com/blog/grails/grails-and-htmlunit/</link>
		<comments>http://www.reverttoconsole.com/blog/grails/grails-and-htmlunit/#comments</comments>
		<pubDate>Sat, 09 May 2009 18:56:14 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[UnitTest]]></category>
		<category><![CDATA[Useful Links]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=360</guid>
		<description><![CDATA[I was struggling to add HtmlUnit to Grails to do some testing when I came upon this. The solution was to remove the HtmlUnit included jar, xml-apis-1.3.04. The error looked like this: loader constraint violation: loader (instance of &#38;amp;lt;bootloader&#38;amp;gt;) previously initiated loading for a different type with name &#34;org/w3c/dom/NamedNodeMap&#34; java.lang.LinkageError: loader constraint violation: loader (instance of ) [...]]]></description>
			<content:encoded><![CDATA[<p>I was struggling to add HtmlUnit to Grails to do some testing <a href="http://jira.codehaus.org/browse/GROOVY-3356">when I came upon this</a>.</p>
<p>The solution was to remove the HtmlUnit included jar, xml-apis-1.3.04.</p>
<p>The error looked like this:</p>
<pre>
loader constraint violation: loader (instance of &amp;amp;lt;bootloader&amp;amp;gt;) previously initiated loading for a different type with name &quot;org/w3c/dom/NamedNodeMap&quot;
java.lang.LinkageError: loader constraint violation: loader (instance of ) previously initiated loading for a different type with name &quot;org/w3c/dom/NamedNodeMap&quot;
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
at java.lang.Class.getMethod0(Class.java:2670)
at java.lang.Class.getMethod(Class.java:1603)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.isDom3Present(ContextFactory.java:301)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.getE4xImplementationFactory(ContextFactory.java:328)
at net.sourceforge.htmlunit.corejs.javascript.Context.getE4xImplementationFactory(Context.java:2175)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.initStandardObjects(ScriptRuntime.java:222)
at net.sourceforge.htmlunit.corejs.javascript.Context.initStandardObjects(Context.java:1069)
at net.sourceforge.htmlunit.corejs.javascript.Context.initStandardObjects(Context.java:1036)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.init(JavaScriptEngine.java:157)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.access$000(JavaScriptEngine.java:68)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$1.run(JavaScriptEngine.java:130)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:515)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:507)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.initialize(JavaScriptEngine.java:141)
at com.gargoylesoftware.htmlunit.WebClient.initialize(WebClient.java:1107)
at com.gargoylesoftware.htmlunit.WebWindowImpl.setEnclosedPage(WebWindowImpl.java:99)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:268)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:127)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:101)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:442)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:329)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:386)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:371)
at UIUnitTests.setUp(UIUnitTests.groovy:12)
at _GrailsTest_groovy$_run_closure4.doCall(_GrailsTest_groovy:202)
at _GrailsTest_groovy$_run_closure2.doCall(_GrailsTest_groovy:146)
at _GrailsTest_groovy$_run_closure1_closure19.doCall(_GrailsTest_groovy:112)
at _GrailsTest_groovy$_run_closure1.doCall(_GrailsTest_groovy:95)
at TestApp$_run_closure1.doCall(TestApp:66)
at gant.Gant$_dispatch_closure4.doCall(Gant.groovy:324)
at gant.Gant$_dispatch_closure6.doCall(Gant.groovy:334)
at gant.Gant$_dispatch_closure6.doCall(Gant.groovy)
at gant.Gant.withBuildListeners(Gant.groovy:344)
at gant.Gant.this$2$withBuildListeners(Gant.groovy)
at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
at gant.Gant.dispatch(Gant.groovy:334)
at gant.Gant.this$2$dispatch(Gant.groovy)
at gant.Gant.invokeMethod(Gant.groovy)
at gant.Gant.processTargets(Gant.groovy:495)
at gant.Gant.processTargets(Gant.groovy:480)
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F&amp;title=Grails+and+HtmlUnit" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F&amp;title=Grails+and+HtmlUnit" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F&amp;title=Grails+and+HtmlUnit" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F&amp;title=Grails+and+HtmlUnit" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F&amp;title=Grails+and+HtmlUnit', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F&amp;title=Grails+and+HtmlUnit" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgrails%2Fgrails-and-htmlunit%2F&amp;title=Grails+and+HtmlUnit" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/grails/grails-and-htmlunit/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>JavaScript Unit Testing</title>
		<link>http://www.reverttoconsole.com/blog/ajax/javascript-unit-testing/</link>
		<comments>http://www.reverttoconsole.com/blog/ajax/javascript-unit-testing/#comments</comments>
		<pubDate>Fri, 24 Apr 2009 22:28:38 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=328</guid>
		<description><![CDATA[TechTalk: Testing Rich Client Web Applications by Jeff Hemminger from Object Partners on Vimeo.]]></description>
			<content:encoded><![CDATA[<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="300" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://vimeo.com/moogaloop.swf?clip_id=4198648&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed type="application/x-shockwave-flash" width="400" height="300" src="http://vimeo.com/moogaloop.swf?clip_id=4198648&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />
<a href="http://vimeo.com/4198648">TechTalk: Testing Rich Client Web Applications by Jeff Hemminger</a> from <a href="http://vimeo.com/user1150787">Object Partners</a> on <a href="http://vimeo.com">Vimeo</a>.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F&amp;title=JavaScript+Unit+Testing" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F&amp;title=JavaScript+Unit+Testing" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F&amp;title=JavaScript+Unit+Testing" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F&amp;title=JavaScript+Unit+Testing" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F&amp;title=JavaScript+Unit+Testing', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F&amp;title=JavaScript+Unit+Testing" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fajax%2Fjavascript-unit-testing%2F&amp;title=JavaScript+Unit+Testing" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/ajax/javascript-unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Headless Javascript Unit Testing</title>
		<link>http://www.reverttoconsole.com/blog/javascript/headless-javascript-unit-testing/</link>
		<comments>http://www.reverttoconsole.com/blog/javascript/headless-javascript-unit-testing/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 13:06:44 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/?p=253</guid>
		<description><![CDATA[I gave a presentation at work a couple of months ago covering JavaScript scoping considerations for a team of Java developers new to JavaScript. During the presentation, I used Rhino to run the examples. I have seen other projects that use Rhino for unit testing, but they seemed a little heavy weight for what I [...]]]></description>
			<content:encoded><![CDATA[<p>I gave a presentation at work a couple of months ago covering JavaScript scoping considerations for a team of Java developers new to JavaScript.</p>
<p>During the presentation, I used <a href="https://developer.mozilla.org/en/Rhino_documentation">Rhino</a> to run the examples. I have <a href="http://httpunit.sourceforge.net/doc/javascript-support.html">seen</a> <a href="http://www.thefrontside.net/crosscheck">other</a> projects that use Rhino for unit testing, but they seemed a little heavy weight for what I wanted to do, which was to write unit tests for the project&#8217;s JavaScript and integrate it into our continuous integration environment.</p>
<p>The following explains what I did instead that seems to work well. I&#8217;d be interested in hearing any alternative suggestions.</p>
<p><span id="more-214"></span></p>
<p>To start with, I used Rhino and <a href="http://code.google.com/p/envjs/">env.js</a> to create a more full featured javascript runtime environment in the jvm, as <a href="http://ejohn.org/projects/bringing-the-browser-to-the-server/">John Resig wrote about a while back</a>. <a href="http://reverttoconsole.com/2008/09/bringing-the-browser-to-the-server-just-discovered-this/">I wrote about this a while back</a>.</p>
<p>Because I wanted to run Rhino and execute JavaScript inside a unit test, it was easiest for me to modify <a href="http://mxr.mozilla.org/mozilla/source/js/rhino/examples/Shell.java">the Shell example provided by the Rhino group</a>.</p>
<p>Note: WordPress was blowing up on me when I tried to show the entire class&#8230; this is the abbreviated version with most of my changes.</p>
<pre>
public class Shell extends ScriptableObject {

    private boolean quitting;
    private static final long serialVersionUID = -5638074146250193112L;
    /**
     * Logger for this class.
     */
    private static final Logger logger = Logger.getLogger(Shell.class);

    @Override
    public String getClassName() {
        return "global";
    }

    public static void print(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) {
        for (int i = 0; i < args.length; i++) {
            if (i > 0) {
                logger.info(" ");
            }

            // Convert the arbitrary JavaScript value into a string form.
            String s = Context.toString(args[i]);

            logger.info(s);
        }
    }

    public void quit() {
        quitting = true;
    }

    public static double version(final Context cx, final Scriptable thisObj,
            final Object[] args, final Function funObj) {
        double result = cx.getLanguageVersion();
        if (args.length > 0) {
            double d = Context.toNumber(args[0]);
            cx.setLanguageVersion((int) d);
        }
        return result;

    }

    public static void load(final Context cx, final Scriptable thisObj,
            final Object[] args, final Function funObj) {
        Shell shell = (Shell) getTopLevelScope(thisObj);
        for (int i = 0; i < args.length; i++) {
            shell.processSource(cx, Context.toString(args[i]));
        }
    }

    public static void assertEquals(final String expected, final String actual) {
        Assert.assertEquals(expected, actual);
    }

    public static void assertNotNull(final Object object) {
        Assert.assertTrue(!(object instanceof org.mozilla.javascript.Undefined));
        Assert.assertTrue("Provided object is null", object != null);
    }

    public static void assertTrue(final boolean condition) {
        Assert.assertTrue(condition);
    }

    public static void assertFalse(final boolean condition) {
        Assert.assertFalse(condition);
    }

}
</pre>
<p>Next I created an Abstract JUnit test that loads my Javascript environment. My setUp method looks something like this:</p>
<pre>
    protected void setUp() throws Exception {
        super.setUp();
        context = Context.enter();
        try {

            context.setOptimizationLevel(-1);
            shell = new Shell();
            context.initStandardObjects(shell);

            // Define some global functions particular to the shell. Note
            // that these functions are not part of ECMA.
            String[] names = { "print", "quit", "version", "load",
                    "assertEquals", "assertNotNull",
                    "assertTrue", "assertFalse"};
            shell.defineFunctionProperties(names, Shell.class,
                                           ScriptableObject.DONTENUM);
            shell.processSource(context, "src/test/resources/scripts/startup.js");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
</pre>
<p>This initializes the JavaScript context and loads the environment-specific javascript I want to test. In my case I wanted to test code that uses <a href="http://extjs.com/">ExtJS</a>. My startup.js script looks like this:</p>
<pre>
load('src/test/resources/scripts/env.js');
window.location='src/test/resources/scripts/empty.html';
document='src/test/resources/scripts/empty.html';
load('src/main/javascript/extjs/adapter/ext/ext-base.js');
load('src/main/javascript/extjs/ext-all-debug.js');
load('src/test/resources/scripts/resource.js');
load('src/test/resources/scripts/testdata.js');
load('target/myappcode.js');
</pre>
<p>Order is important here. First, I load env.js. Next I set values for window.location and document. I don't use either explicitly, but some of the other files look for them. Then I load extjs, and my data and app code.</p>
<p>The best part about this arrangement is the predefined functions provided by the shell class. I can easily reference junit assert statements from within my javascript test.</p>
<p>Here is an example JUnit class:</p>
<pre>
public class PhoneNumberTest extends AbstractJSTestCase {

    public PhoneNumberTest(final String name) {
        super(name);
    }

   public void testPhoneCountryCodeRender() {
       processScript("src/test/javascript/PhoneCountryCodeRenderTest.js");
   }

   public void testCreateGrid() {
       processScript("src/test/javascript/PhoneNumberCreateGridTest.js");
   }

}
</pre>
<p>and the javascript test code it calls:</p>
<pre>

var phoneNumber = new edit.form.PhoneNumber();

assertNotNull(phoneNumber);
assertNotNull(profile);

var grid = phoneNumber.createGrid(profile);

assertNotNull(grid);

var store = grid.store;

assertNotNull(store);

assertTrue(store.getCount() === 2);

var record1 = store.getAt(0);
assertNotNull(record1);
var record2 = store.getAt(1);
assertNotNull(record2);

print(record1.data.phoneNumber);
print(record2.data.phoneNumber);

print(record1.data.extension);
print(record2.data.extension);

// Now remove the access code from the phone number
record1.data.phoneNumber = PhoneUtils.removeAccessCode(record1);
print(record1.data.phoneNumber);

record2.data.phoneNumber = PhoneUtils.removeAccessCode(record2);
print(record2.data.phoneNumber);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/javascript/headless-javascript-unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EasyMock IllegalStateException</title>
		<link>http://www.reverttoconsole.com/blog/unittest/easymock-illegalstateexception/</link>
		<comments>http://www.reverttoconsole.com/blog/unittest/easymock-illegalstateexception/#comments</comments>
		<pubDate>Tue, 18 Nov 2008 11:57:13 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/?p=244</guid>
		<description><![CDATA[I had a case this morning reworking a test after I&#8217;d modified a method signature, from: expect(mockRestProxy.getProxiedResource((String) anyObject())) .andReturn("{policies}"); to expect(mockRestProxy.getProxiedResource((String) anyObject(), userIdentity)) .andReturn("{policies}"); I received a stacktrace like this: java.lang.IllegalStateException: 2 matchers expected, 1 recorded. at org.easymock.internal.ExpectedInvocation.createMissingMatchers(ExpectedInvocation.java:41) at org.easymock.internal.ExpectedInvocation.&#60;init&#62;(ExpectedInvocation.java:33) at org.easymock.internal.ExpectedInvocation.&#60;init&#62;(ExpectedInvocation.java:26) at org.easymock.internal.RecordState.invoke(RecordState.java:64) at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:24) at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:45) at $Proxy0.getProxiedResource(Unknown Source) ... To quote the [...]]]></description>
			<content:encoded><![CDATA[<p>I had a case this morning reworking a test after I&#8217;d modified a method signature, from:</p>
<pre>
        expect(mockRestProxy.getProxiedResource((String) anyObject()))
            .andReturn("{policies}");
</pre>
<p>to</p>
<pre>
        expect(mockRestProxy.getProxiedResource((String) anyObject(), userIdentity))
            .andReturn("{policies}");
</pre>
<p>I received a stacktrace like this:</p>
<pre>
java.lang.IllegalStateException: 2 matchers expected, 1 recorded.
	at org.easymock.internal.ExpectedInvocation.createMissingMatchers(ExpectedInvocation.java:41)
	at org.easymock.internal.ExpectedInvocation.&lt;init&gt;(ExpectedInvocation.java:33)
	at org.easymock.internal.ExpectedInvocation.&lt;init&gt;(ExpectedInvocation.java:26)
	at org.easymock.internal.RecordState.invoke(RecordState.java:64)
	at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:24)
	at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:45)
	at $Proxy0.getProxiedResource(Unknown Source)
...
</pre>
<p>To quote the easymock documentation,</p>
<blockquote><p>
To match an actual method call on the Mock Object with an expectation, Object arguments are by default compared with equals(). This may lead to problems.
</p></blockquote>
<p>this describes the problem.</p>
<p>The solution appears to be here:</p>
<blockquote><p>
If you would like to use matchers in a call, you have to specify matchers for all arguments of the method call.<br />
There are a couple of predefined argument matchers available.
</p></blockquote>
<p>My solution was in fact to use one of the predefined matchers:</p>
<pre>
        expect(mockRestProxy.getProxiedResource((String) anyObject(), (UserIdentity) anyObject()))
            .andReturn("{policies}");
</pre>
<p>One thing I don&#8217;t really understand is why EasyMock wouldn&#8217;t allow you to match the method signature with a combination of matchers and objects. I wouldn&#8217;t think the logic for a heterogenous object equals check would be that terribly complex.</p>
<p>The <a href="http://www.easymock.org/EasyMock2_2_Documentation.html">EasyMock Mockumentation</a> (just a play on words, it&#8217;s really not too bad).</p>
<p><strong>Hat Tip to <a href="http://marcels-javanotes.blogspot.com/2007/03/easymock-and-illegalstateexception.html">Marcels Javanotes</a></strong></p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F&amp;title=EasyMock+IllegalStateException" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F&amp;title=EasyMock+IllegalStateException" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F&amp;title=EasyMock+IllegalStateException" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F&amp;title=EasyMock+IllegalStateException" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F&amp;title=EasyMock+IllegalStateException', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F&amp;title=EasyMock+IllegalStateException" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Funittest%2Feasymock-illegalstateexception%2F&amp;title=EasyMock+IllegalStateException" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/unittest/easymock-illegalstateexception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automated Unit Testing with DBUnit, Hsqldb in Spring &amp; Hibernate projects</title>
		<link>http://www.reverttoconsole.com/blog/hibernate-jpa/automated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects/</link>
		<comments>http://www.reverttoconsole.com/blog/hibernate-jpa/automated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects/#comments</comments>
		<pubDate>Sat, 07 Jun 2008 23:16:11 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Hibernate/JPA]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>
		<category><![CDATA[hsqldb]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/archives/157</guid>
		<description><![CDATA[If your project has a lot of unit testing in Java and you use continuous builds (CruiseControl) to automate, it is often difficult to automate tests which connect to Database (Dao and integration tests). For most companies, having a dedicated Oracle schema for testing is expensive. Also, sometimes, developers need their own instances of schemas [...]]]></description>
			<content:encoded><![CDATA[<p>If your project has a lot of unit testing in Java and you use continuous builds (CruiseControl) to automate, it is often difficult to automate tests which connect to Database (Dao and integration tests). For most companies,  having a dedicated Oracle schema for testing is expensive. Also, sometimes, developers need their own instances of schemas to test on, which again is not possible with a corporate DBA on Oracle.  Obviously writing unit tests connecting to the same instance where dev environment is setup is extremely unpleasant.</p>
<p>What do you do then?</p>
<p>Welcome to <a href="http://schemamule.sourceforge.net/index.html">Schemamule</a>. It&#8217;s a tiny jar file and has a single ant task which copies the entire Oracle Schema and generates a Hsqldb database. <strong>YES. </strong>It replicates an entire Oracle Schema into a hsqldb in seconds! You can either use it as an in memory database for your automated unit testing or as dev only local database for unit testing. For more details, read the original blog <a href="http://www.moseshohman.com/blog/2006/05/23/schemamule-10-released/">here</a>.</p>
<p>Let me iterate the advantages:-</p>
<p>&#8211; Can write database dependent test cases<br />
&#8211; Need not connect to a network for running tests<br />
&#8211; Database tests run at blazing speed, as now they&#8217;re on hsqldb</p>
<p>I worked with one of the developers &#8212; Rhett Sutphin, in my earlier project. He&#8217;s a brilliant programmer. I&#8217;ve also reused it in one of my projects at a financial firm, it works great and is amazingly productive once you have setup a framework based on <a href="http://dbunit.sourceforge.net/">dbunit</a>. Wait, what is dbunit? I&#8217;m not going into the details but it&#8217;s a no-brainer that if you use hibernate and junit, you better get started on using dbunit for unit testing backed by xml datasets instead of the cumbersome setup/teardown methods to populate data for each junit test case</p>
<p>We have a sample project checked into RTC&#8217;s sourceforge (We call it <a href="http://sourceforge.net/projects/helloworld2/" target="_blank">helloworld2</a>), with custom classes on top of DBUnit (most of it has been written by the author of Schemamule).</p>
<p>My example considers of an entity, Foo with FooDao, mapped to a table Foo<em>.</em> For simplicity, I assume one field called name. As a step by step tutorial on extending DBUnit Unit Testing ,  I&#8217;ll show how simple it is to write a Dao based unit test case using Dbunit, Spring and Hibernate (of course on our generated hsqldb)</p>
<p>Step 1:Create an Hsqldb database from Oracle</p>
<p>Download <a href="https://sourceforge.net/project/showfiles.php?group_id=166480">Schemamule</a> and run the following ant task</p>
<pre>
&lt;schemacopy xmlns=&quot;http://bioinformatics.northwestern.edu/schemamule&quot;&gt;
    &lt;to uri=&quot;jdbc:hsqldb:file:${basedir}/hsqldb/mydb&quot; username=&quot;sa&quot;&gt;
    &lt;from uri=&quot;jdbc:oracle:thin:mydb&quot; username=&quot;scott&quot; password=&quot;tiger&quot;&gt;
&lt;/from&gt;
&lt;/to&gt;&lt;/schemacopy&gt;
</pre>
<p>Step 2: Setup DBUnit<br />
Download the latest version of <a href="http://dbunit.sourceforge.net/">dbunit </a>(jdk1.4 or jdk5)</p>
<p>Step 3: Download the svn repository (0r copy by browsing svn) Revert To Console&#8217;s sample test utility classes and example DBUnit tutorial from sourceforge <a href="http://sourceforge.net/svn/?group_id=200388">here</a>.</p>
<p>- Checkout under projects/unit-test.<br />
- I&#8217;m not providing a complete working example with spring/hibernate configuration, as I presume you are running under an environment where you already have a this configured with an Oracle database.</p>
<p>- the utility classes include the following classes<br />
- CoreTestCase &#8212; An extension on JUnit with much more useful assert statements<br />
- ApplicationTestCase &#8212; All the unit tests in your Spring/Hibernate project should extend this class<br />
- DaoTestCase &#8212; All your Dao Tests should extend this class<br />
- ContextTools &#8211; The class which reads your applicationContext-xyz.xml file, where hibernate session is configured<br />
- Sample Dao and entity</p>
<p>Configure these files in your project, which can read the applicationContext from the classpath (for the tests to work!)</p>
<p>Step 4:With all this configured, let&#8217;s write a simple Dao Test</p>
<pre>
public class FooDAOTest extends DaoTestCase {
    FooDao dao = (FooDao)getApplicationContext().getBean(&quot;fooDao&quot;);
         // assuming that your spring config has a bean-id 'fooDao'
	 public void testGetById() throws Exception {
            Foo foo = (Foo)dao.getById(1);
            assertEquals(&quot;revert to console&quot;, foo.getName());
	 }
}</pre>
<p>By Default, DBUnit assumes a test data xml file in the same testdata/FooDaoTest.xml (you can override this). Now, lets see the dataset</p>
<pre>
&lt;dataset&gt;
&lt;table name=&quot;FOO&quot;&gt;&lt;column&gt;name&lt;/column&gt;
        &lt;row&gt;
            &lt;value&gt;revert to console&lt;/value&gt;
         &lt;/row&gt;&lt;/table&gt;
&lt;/dataset&gt;
</pre>
<p>That&#8217;s it! For all the configuration that I&#8217;ve showed you (which will take some time to setup), all you need to do to write another test is, to write another method with testdata! This setup will create,drop the testdata on the generated HsqlDb schema before/after each test. What more, because, it is in memory, you can even run, Dao Tests and complete round trip unit tests automated in your nightly builds, without coupling to an existing Oracle Schema.</p>
<p>There are some limitations to Schemamule though. I had to customize it for my project as we were using DB Views. I finally got it working after modifying the sourcecode. Unfortunately I could never put that back into Schemamule as a patch but I recommend downloading the source and try it for yourself. It&#8217;s a great example on understanding how Spring&#8217;s Jdbc template works and can be extended.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/hibernate-jpa/automated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Limitations of AbstractTransactionalDataSourceSpringContextTests</title>
		<link>http://www.reverttoconsole.com/blog/spring/limitations-of-abstracttransactionaldatasourcespringcontexttests/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/limitations-of-abstracttransactionaldatasourcespringcontexttests/#comments</comments>
		<pubDate>Tue, 13 May 2008 21:35:13 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/archives/180</guid>
		<description><![CDATA[This has apparently gotten a fair amount of attention over the last year or so, but I never encountered it until today- call me lucky. Here&#8217;s the situation, you&#8217;re using Spring MVC and you have a controller that extends another controller (A->B). Your unit test extends AbstractTransactionalDataSourceSpringContextTests, and makes use of autowiring. You write your [...]]]></description>
			<content:encoded><![CDATA[<p>This has apparently gotten a fair amount of attention over the last year or so, but I never encountered it until today- call me lucky. Here&#8217;s the situation, you&#8217;re using <a href="http://www.springframework.org/about">Spring MVC</a> and you have a controller that extends another controller (A->B).</p>
<p>Your unit test extends <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.html">AbstractTransactionalDataSourceSpringContextTests</a>, and makes use of <a href="http://groups.google.com/group/EtoE/browse_thread/thread/9306c581470b47cb/31a62772d677bd12">autowiring</a>.</p>
<p>You write your test, run it, and receive something like this:</p>
<pre>
 Unsatisfied dependency expressed through bean property 'aController':
 No unique bean of type [org.reverttoconsole.majorapplication.controller.aController] is defined:
  expected single matching bean but found 2: [aController.htm, bController.htm]
</pre>
<p>I tried using <a href="http://static.springframework.org/spring/docs/2.5.x/reference/testing.html">annotations</a>, using @Autowire and @Resource, but in the end had to refactor my code to fit the tests&#8230; by creating an Abstract class that both controllers could extend.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/limitations-of-abstracttransactionaldatasourcespringcontexttests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Integration Testing with HSQLDB</title>
		<link>http://www.reverttoconsole.com/blog/unittest/java-integration-testing-with-hsqldb/</link>
		<comments>http://www.reverttoconsole.com/blog/unittest/java-integration-testing-with-hsqldb/#comments</comments>
		<pubDate>Fri, 18 May 2007 13:40:30 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[UnitTest]]></category>
		<category><![CDATA[hsqldb]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/archives/108</guid>
		<description><![CDATA[I&#8217;m a fairly recent convert to unit testing, but still when I&#8217;m under pressure to get something finished, I skip right to integration tests. Despite the guilt I still use the junit framework for these integration tests&#8230; I know the unit testing purists will be rolling their eyes at this point, but this is something [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a fairly recent convert to unit testing, but still when I&#8217;m under pressure to get something finished, I skip right to integration tests. Despite the guilt I still use the <a href="http://www.junit.org/index.htm">junit</a> framework for these integration tests&#8230; I know the unit testing purists will be rolling their eyes at this point, but this is something I&#8217;ve found useful to do.</p>
<p>A while back <a href="http://reverttoconsole.com/archives/90#more-90">I wrote about using hsqldb</a> in unit/integration tests running in memory. The process works well because you can effectively avoid having to clean up the database before running a test, and you don&#8217;t have to worry about closing the connections in the tearDown() method either. Just kill the process and the database goes away. Provide a setup sql script and load that before running your test, and you&#8217;re golden.</p>
<p>But for more involved integration tests, it&#8217;s nice to be able to see the data that&#8217;s been modified. Or write a test that performs a first phase of data manipulation, followed by a second test that relies on the output of the first. This can be accomplished by an in-memory database, but it&#8217;s more satisfying for me to actually see what occurred after the test has run. I&#8217;m probably just not detail-oriented enough to set up a test thoroughly while I&#8217;m doing development, and I like being able to exam the database results visually for that added level of comfort.</p>
<p>Hsqldb provides some really nice configuration options for running the database as a server:</p>
<li>
<ul>There&#8217;s Standard Standalone server.</ul>
<ul>You can also run the standalone server as an in-memory server</ul>
<ul>There&#8217;s also a webserver server mode that makes use of http</ul>
<ul>As of 1.7.2 hsqldb provides the ability to run more than one database in multiple server modes. (ie simultaneous access to multiple in-process and memory-only databases)</ul>
</li>
<p>Read on to see how I set this up for my tests:</p>
<p><span id="more-96"></span></p>
<p>In my tests, I need to read from one db and load into another. The problem is that the database server I could use is in a remote office over a crappy network. So there&#8217;s a strong motivation for me to run my tests locally. I needed to set up two databases, and as I said earlier, I want to be able to see the results of my work. So (this is the part where the ruby on rails people laugh):</p>
<ol>
<li>Configure two databases for my server</li>
<li>Configure my database explorer client</li>
<li>Configure my app to work with hsqldb</li>
</ol>
<h3>Configure two databases for my server</h3>
<p>To configure this in Eclipse, you&#8217;ll need to create a Java App to run. <code>Run->Run, Java Application, right-click New</code>. Main Class will be <strong>org.hsqldb.Server</strong>. I use a separate eclipse project to store my jars, so I selected that as my project. Next add the hsqldb.jar to the classpath. You can also specify arguments, but I opted to use a server.properties file instead. You can apply or save the app now.</p>
<p>Since I specified my jar project for the app I created, I created a file, server.properties in the base directory of that project. The file looks like this:</p>
<pre>
#this is the default so I may not actually need this
server.port=9001

#mounts a file-based (persistent) database with alias 'clinicalconcept'
#database connection url would be 'jdbc:hsqldb:hsql://localhost/clinicalconcept'
#but '/clinicalconcept' can be omitted because database.0 is the default
server.database.0=file:C:/eceppda/work/schemadb
server.dbname.0=clinicalconcept

#mounts a file-based (persistent) database with the alias 'staged'
#datbase connection url would be 'jdbc:hsqldb:hsql://localhost/staged'
server.database.1=file:C:/eceppda/work/stagedb
server.dbname.1=staged

#Display messages in console
server.silent=false
</pre>
<p>There are of course more options you can <a href="http://hsqldb.org/doc/guide/ch04.html#N10AA9">view them here</a>.</p>
<h3>Configure my database explorer client</h3>
<p>I use <a href="http://www.myeclipseide.com/">MyEclipse</a>. I like it a lot. It has a <a href="http://www.myeclipseide.com/htmlpages-func-display-pid-16.html">database explorer plugin</a>, <a href="http://www.myeclipseide.com/module-htmlpages-display-pid-1.html">among other things</a>. So I use this database explorer. I had to specify that I was connecting to a hsqldb, and provide it with the hsqldb jar. For connection strings, I used these (one for each database):</p>
<ul>
<li><strong>jdbc:hsqldb:hsql://localhost/clinicalconcept</strong></li>
<li><strong>jdbc:hsqldb:hsql://localhost/staged</strong></li>
</ul>
<h3>Configure my app to work with hsqldb</h3>
<p>Lastly, in the app I&#8217;m writing I created a properties file to hold the database information:</p>
<pre>
# staging database
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:hsql://localhost/clinicalconcept
db.username=sa
db.password=

stage.driver=org.hsqldb.jdbcDriver
stage.url=jdbc:hsqldb:file:C:/eceppda/stagedb/stagedb
stage.username=sa
stage.password=
</pre>
<p>Then in my spring config I specify the propertyconfigurator and my datasources:</p>
<pre>

&lt;bean id=&quot;propertyConfigurer&quot; class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;&gt;
		&lt;property name=&quot;locations&quot;&gt;
			&lt;list&gt;
				&lt;value&gt;com/my/shite/resource/updater.properties&lt;/value&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;dbSourceDS&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;&gt;
		&lt;property name=&quot;driverClassName&quot;&gt;
			&lt;value&gt;${db.driver}&lt;/value&gt;
		&lt;/property&gt;
		&lt;property name=&quot;url&quot;&gt;
			&lt;value&gt;${db.url}&lt;/value&gt;
		&lt;/property&gt;
		&lt;property name=&quot;username&quot;&gt;
			&lt;value&gt;${db.username}&lt;/value&gt;
		&lt;/property&gt;
		&lt;property name=&quot;password&quot;&gt;
			&lt;value&gt;${db.password}&lt;/value&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;stageSource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;&gt;
		&lt;property name=&quot;driverClassName&quot;&gt;
			&lt;value&gt;${stage.driver}&lt;/value&gt;
		&lt;/property&gt;
		&lt;property name=&quot;url&quot;&gt;
			&lt;value&gt;${stage.url}&lt;/value&gt;
		&lt;/property&gt;
		&lt;property name=&quot;username&quot;&gt;
			&lt;value&gt;${stage.username}&lt;/value&gt;
		&lt;/property&gt;
		&lt;property name=&quot;password&quot;&gt;
			&lt;value&gt;${stage.password}&lt;/value&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
</pre>
<p>And that should do it. Run the app you configured in spring, you should see more verbose output that will say that it&#8217;s read the server.properties file. Refer to <a href="http://reverttoconsole.com/archives/90#more-90">my previous post</a> on loading data into the db&#8217;s for your tests&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/unittest/java-integration-testing-with-hsqldb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

