<?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>Grails Geek &#187; mockDomain</title>
	<atom:link href="http://grailsgeek.com/tag/mockdomain/feed/" rel="self" type="application/rss+xml" />
	<link>http://grailsgeek.com</link>
	<description>Grails tips I wanna share with you ;)</description>
	<lastBuildDate>Sun, 01 Nov 2009 13:29:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using standalone GORM for testing</title>
		<link>http://grailsgeek.com/2009/11/using-standalone-gorm-for-testing/</link>
		<comments>http://grailsgeek.com/2009/11/using-standalone-gorm-for-testing/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 13:29:51 +0000</pubDate>
		<dc:creator>Alexander Naumenko</dc:creator>
				<category><![CDATA[the rest]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[mockDomain]]></category>
		<category><![CDATA[standalone gorm]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://grailsgeek.com/?p=67</guid>
		<description><![CDATA[Recently I was stuck with persistence testing. I like to write simple unit tests and run them from my favorite IDE (Intellij IDEA forever!), but there was no luck with GORM Criterias testing. My case is simple: I have Grails Service which using criteria to fetch some objects from the database. Testing with mockDomain() won&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Recently I was stuck with persistence testing. I like to write simple unit tests and run them from my favorite IDE (Intellij IDEA forever!), but there was no luck with GORM Criterias testing. My case is simple: I have Grails Service which using criteria to fetch some objects from the database. Testing with mockDomain() won&#8217;t work since you need Hibernate support. Of course you could still write integration tests as described in Grails tutorial, but I just didn&#8217;t want to.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">First off I looked through google&#8217;s top 10 about the subject, but after few hours of trials I was still where I started.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">I decided to look on Grails sources and (voilà!) I found HibernateCriteriaBuilderTests. Which has tested exactly what I messed with.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">I&#8217;m not going to share all things I&#8217;ve done until I got finally working abstract test case (based on AbstractGrailsHibernateTests) . You should just derive your test from test case below and use Grails domain objects in your test as usual. Also I&#8217;ll provide two classes MockGrailsPluginManager and MockHibernateGrailsPlugin. Both of them were taken as is from Grails test sources.</div>
<p>Recently I was stuck with persistence testing. I like to write simple unit tests and run them from my favorite IDE (<span style="color: #333399;">Intellij IDEA</span> forever!), but there was no luck with<span style="color: #333399;"> GORM Criterias</span> testing. My case is simple: I have Grails Service which using criteria to fetch some objects from the database. Testing with <span style="color: #333399;">mockDomain()</span> won&#8217;t work since you need <span style="color: #333399;">Hibernate</span> support. Of course you could still write integration tests as described in Grails tutorial, but I just didn&#8217;t want to.</p>
<p><span style="background-color: #ffffff;">First off I looked through google&#8217;s top 10 about the subject, but after few hours of trials I was still where I started.</span></p>
<p><span style="background-color: #ffffff;">I decided to look on Grails sources and (voilà!) I found <span style="color: #333399;">HibernateCriteriaBuilderTests</span>. Which has tested exactly what I messed with.</span></p>
<p><span style="background-color: #ffffff;">I&#8217;m not going to share all things I&#8217;ve done until I got finally working abstract test case (based on <span style="color: #333399;">AbstractGrailsHibernateTests</span>) . You should just derive your test from test case below and use Grails domain objects in your test as usual. Also I&#8217;ll provide two classes <span style="color: #333399;">MockGrailsPluginManager</span> and <span style="color: #333399;">MockHibernateGrailsPlugin</span>. Both of them were taken as is from Grails test sources.</span></p>
<h4><span style="background-color: #ffffff;"> <strong>AbstractPersistenceTestCase</strong></span></h4>
<pre class="brush:groovy">package com.grailsgeek

import com.grailsgeek.MockHibernateGrailsPlugin
import grails.test.GrailsUnitTestCase
import groovy.lang.ExpandoMetaClass
import groovy.lang.ExpandoMetaClassCreationHandle
import groovy.lang.GroovyClassLoader
import groovy.lang.GroovySystem
import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator
import org.codehaus.groovy.grails.plugins.datasource.DataSourceGrailsPlugin
import org.codehaus.groovy.grails.plugins.i18n.I18nGrailsPlugin
import org.codehaus.groovy.grails.support.MockApplicationContext
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.springframework.context.ApplicationContext
import org.springframework.context.support.StaticMessageSource
import org.springframework.orm.hibernate3.SessionFactoryUtils
import org.springframework.orm.hibernate3.SessionHolder
import org.springframework.transaction.support.TransactionSynchronizationManager
import org.codehaus.groovy.grails.plugins.*

abstract class AbstractPersistenceTestCase extends GrailsUnitTestCase {
    GroovyClassLoader gcl = new GroovyClassLoader(this.getClass().classLoader)
    MockApplicationContext ctx;
    ApplicationContext appCtx
    SessionFactory sessionFactory
    Session session

    protected void setUp() {
        super.setUp();

        ExpandoMetaClass.enableGlobally()

        GroovySystem.metaClassRegistry.metaClassCreationHandle = new ExpandoMetaClassCreationHandle();

        gcl.parseClass('''
dataSource {
	pooled = true
	driverClassName = "org.hsqldb.jdbcDriver"
	username = "sa"
	password = ""
    dbCreate = "create-drop" // one of 'create', 'create-drop','update'
    url = "jdbc:hsqldb:mem:testDB"
}
hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='com.opensymphony.oscache.hibernate.OSCacheProvider'
}
''', "DataSource")

        ctx = new MockApplicationContext();

        def classes = getDomainClasses()

        gcl.getLoadedClasses().each {
            classes &lt;&lt; it
        }

        def ga = new DefaultGrailsApplication(classes as Class[], gcl)
        def mockManager = new MockGrailsPluginManager(ga)
        ctx.registerMockBean("manager", mockManager)
        PluginManagerHolder.setPluginManager(mockManager)

        def dependentPlugins = [
                DataSourceGrailsPlugin,
                DomainClassGrailsPlugin,
                I18nGrailsPlugin,
                MockHibernateGrailsPlugin
        ].collect { new DefaultGrailsPlugin(it, ga)}

        dependentPlugins.each { mockManager.registerMockPlugin(it); it.manager = mockManager }
        mockManager.doArtefactConfiguration();
        ctx.registerMockBean(PluginMetaManager.BEAN_ID, new DefaultPluginMetaManager());

        ga.initialise()
        ga.setApplicationContext(ctx);
        ApplicationHolder.setApplication(ga)
        ctx.registerMockBean(GrailsApplication.APPLICATION_ID, ga);
        ctx.registerMockBean("messageSource", new StaticMessageSource())

        def springConfig = new DefaultRuntimeSpringConfiguration(ctx, gcl)
        dependentPlugins*.doWithRuntimeConfiguration(springConfig)

        appCtx = springConfig.getApplicationContext()
        dependentPlugins*.doWithApplicationContext(appCtx)

        mockManager.applicationContext = appCtx
        mockManager.doDynamicMethods()

        sessionFactory = appCtx.getBean(GrailsRuntimeConfigurator.SESSION_FACTORY_BEAN);

        if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
            session = sessionFactory.openSession();
            TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
        }
    }

    abstract List getDomainClasses()

    protected void tearDown() {
        if (TransactionSynchronizationManager.hasResource(this.sessionFactory)) {
            SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(this.sessionFactory);
            org.hibernate.Session s = holder.getSession();
            //s.flush();
            TransactionSynchronizationManager.unbindResource(this.sessionFactory);
            SessionFactoryUtils.releaseSession(s, this.sessionFactory);
        }

        ApplicationHolder.setApplication(null)
        ExpandoMetaClass.disableGlobally()
        PluginManagerHolder.setPluginManager(null)

        super.tearDown();
    }
}</pre>
<h4>MockGrailsPluginManager</h4>
<pre class="brush:groovy">package com.grailsgeek;

import groovy.lang.GroovyClassLoader;
import junit.framework.Assert;
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.plugins.exceptions.PluginException;
import org.springframework.core.io.Resource;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Map
import org.codehaus.groovy.grails.plugins.AbstractGrailsPluginManager
import org.codehaus.groovy.grails.plugins.GrailsPlugin;

/**
 * @author Graeme Rocher
 * @since 0.4
 *
 */

public class MockGrailsPluginManager extends AbstractGrailsPluginManager {
    private ServletContext servletContext;
    private boolean checkForChangesExpected = false;

    public ServletContext getServletContext() {
        return servletContext;
    }

    public MockGrailsPluginManager(GrailsApplication application) {
		super(application);
		loadPlugins();
	}

	public MockGrailsPluginManager() {
		this(new DefaultGrailsApplication(new Class[0], new GroovyClassLoader()));
	}

	public GrailsPlugin getGrailsPlugin(String name) {
		return this.plugins.get(name);
	}

	public GrailsPlugin getGrailsPlugin(String name, BigDecimal version) {
		return this.plugins.get(name);
	}

	public boolean hasGrailsPlugin(String name) {
		return this.plugins.containsKey(name);
	}

	public void registerMockPlugin(GrailsPlugin plugin) {
		this.plugins.put(plugin.getName(), plugin);
		this.pluginList.add(plugin);
	}

	public void loadPlugins() throws PluginException {
		this.initialised = true;
	}

	public void checkForChanges() {
        Assert.assertTrue(this.checkForChangesExpected);
        this.checkForChangesExpected = false;
    }

	public void doWebDescriptor(Resource descriptor, Writer target) {
		// do nothing
	}

	public void doWebDescriptor(File descriptor, Writer target) {
		// do nothing
	}

	public boolean isInitialised() {
		return true;
	}

    public void refreshPlugin(String name) {
        GrailsPlugin plugin = plugins.get(name);
        if(plugin != null) {
            plugin.refresh();
        }
    }

    public Collection getPluginObservers(GrailsPlugin plugin) {
        throw new UnsupportedOperationException("The class [MockGrailsPluginManager] doesn't support the method getPluginObservers");
    }

    public void informObservers(String pluginName, Map event) {
        // do nothing
    }

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void expectCheckForChanges() {
        Assert.assertFalse(this.checkForChangesExpected);
        this.checkForChangesExpected = true;
    }

    public void verify() {
        Assert.assertFalse(this.checkForChangesExpected);
    }
}</pre>
<h4>MockHibernateGrailsPlugin</h4>
<pre class="brush:groovy">package com.grailsgeek

import org.codehaus.groovy.grails.plugins.orm.hibernate.HibernatePluginSupport

class MockHibernateGrailsPlugin {
    def version = grails.util.GrailsUtil.getGrailsVersion()
    def dependsOn = [dataSource: version,
            i18n: version,
            core: version,
            domainClass: version]

    def loadAfter = ['controllers']
    def doWithSpring = HibernatePluginSupport.doWithSpring
    def doWithDynamicMethods = HibernatePluginSupport.doWithDynamicMethods
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://grailsgeek.com/2009/11/using-standalone-gorm-for-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
