<?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>Jayway Team Blog &#187; mock</title>
	<atom:link href="http://blog.jayway.com/tag/mock/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Spring Integration Tests, Part II, Using Mock Objects</title>
		<link>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/</link>
		<comments>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 20:17:27 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10532</guid>
		<description><![CDATA[In the previous post, I wrote how you can use Spring's FactoryBean to facilitate the creation of mock objects for Spring integration tests. Now, it is time to use the EasyMockFactoryBean (in this post EasyMock has been used for creating mock objects, but a similar approach applies to Mockito as well. Start by looking at [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous post, I wrote how you can use Spring's <code>FactoryBean</code> to facilitate the <a href="http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/">creation of mock objects</a> for Spring integration tests. Now, it is time to use the <a href="https://gist.github.com/1397610#file_easy_mock_factory_bean.java">EasyMockFactoryBean</a> <small>(in this post <a href="http://www.easymock.org">EasyMock</a> has been used for creating mock objects, but a similar approach applies to <a href="http://www.mockito.org">Mockito</a> as well. Start by looking at the <a href="https://gist.github.com/1397610#file_mockito_factory_bean.java">MockitoFactoryBean</a>)</small>.</p>
<p>Next, imagine that the <code>Facade</code> class and the <code>Delegate</code> interface below are part of a bigger system: </p>
<p><script src="https://gist.github.com/1427987.js?file=Facade.java"></script><br />
<script src="https://gist.github.com/1427987.js?file=Delegate.java"></script></p>
<p>Create a matching <a href="https://gist.github.com/1427987#file_easymock_test_config.xml">easymock-test-config.xml</a> <small>(or <a href="https://gist.github.com/1427987#file_movkito_test_config.xml">mockito-test-config.xml</a>)</small>.</p>
<p>Now, we have all the bits and pieces that are needed to start writing the integration test. We start simple to make sure that we autowiring and Spring context has been configured correctly:<br />
<script src="https://gist.github.com/1427987.js?file=InitialTest.java"></script></p>
<p>The test is executed and it passes without any problem.</p>
<p>A second test is added to the same file with some added mock behavior:<br />
<script src="https://gist.github.com/1427987.js?file=SecondTest.java"></script></p>
<p>Excellent, that test also passes.</p>
<p>Now that we have warmed up, we add a third test to the test class:<br />
<script src="https://gist.github.com/1427987.js?file=ThirdTest.java"></script><br />
As expected, this test also passes without any problem.</p>
<p>Unfortunately, that is not always true. A closer investigation reveals that all tests pass when they are executed <i>individually</i>. When executing all three tests (either from the IDE or from a build tool like Maven), the third test <i>fails</i> unexpectedly:</p>
<pre>
java.lang.AssertionError:
  Unexpected method call Delegate.doSomethingElse():
        at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
	at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
	at $Proxy8.doSomethingElse(Unknown Source)
        [...]
</pre>
<p>This is EasyMock telling us that the mock object is in the wrong state. An EasyMock mock object goes through a series of steps:</p>
<ol>
<li><i>Initialization</i> - Instantiate the mock object.</li>
<li><i>Record</i> - Record the expectations of the mock object.</li>
<li><i>Replay</i> - Call <code>replay()</code> on the mock object so that it can replay the recorded state.</li>
<li><i>Test</i> - Execute the test assertions.</li>
<li><i>Verify</i> - Call <code>verify()</code> on the mock object to certify that the recorded mock expectations are fulfilled.</li>
</ol>
<p>In an ordinary unit test, the mock object is thrown away after the <i>verify</i> phase, a new mock instance is created before the next test that can be used to <i>record</i> the new behavior. However, since we are creating a Spring integration test, there is one more thing to consider.</p>
<h2>Reused beans</h2>
<p>In the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testing-ctx-management">testing chapter</a> of the Spring manual it is stated that:</p>
<blockquote><p>By default, once loaded, the configured ApplicationContext and all of its beans are reused for each test method. Thus the setup cost is incurred only once (per test fixture), and subsequent test execution is much faster.</p></blockquote>
<p>Consequently, all Spring beans, including mocked beans, will preserve their state between different test methods. The mock object will be in the <i>verify</i> state when the last test begins and not in the <i>record</i> state when <code>delegateMock.doSomethingElse()</code> is called. To solve the problem, we need some mechanism to ensure that the mock object is in a known, well-defined state before each test.</p>
<h2>Reset mocks</h2>
<p>Both EasyMock and Mockito provide methods to <code>reset()</code> the state of the mocked objects. Normally, resetting mock objects in the middle of a test method is considered to be a <a href="http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#17">potential code smell</a>, because it is likely that you are testing too much and that the test could be refactored into two separate tests accordingly. Nonetheless, resetting the mock instance <a href="http://junit.sourceforge.net/javadoc/org/junit/Before.html">@Before</a> each test allow us to keep the same mock instance through the entire lifetime of the test class and yet put it in the <i>record</i> state when before each test starts:</p>
<p><script src="https://gist.github.com/1427987.js?file=SetUp.java"></script></p>
<p>When executing all tests in the test class, we see that that the problem has been solved and all tests pass.<br />
For reference, click the link for the full source code of the <a href="https://gist.github.com/1427987#file_easy_mock_facade_test.java">EasyMock test class</a> <small>(and the <a href="https://gist.github.com/1427987#file_mockito_facade_test.java">Mockito test class</a>)</small>.</p>
<h2>Comments</h2>
<p>You may choose to reset the mocks <a href="http://junit.sourceforge.net/javadoc/org/junit/After.html">@After</a> each test, the result will be the same.</p>
<p>The <code>reset()</code> method is called <i>between</i> the different test methods (because of the nature of <code>@After</code> and <code>@Before</code>), so the code smell of calling reset <i>within</i> a test is avoided.</p>
<p>Tests written using Mockito mocks are generally more tolerant for this kind of problem. In contrast to EasyMock, Mockito has no <code>replay()</code> method and no notion of steps. Therefore, it is possible to add additional mock expectations and to replace existing expectations, both after the test has been executed as well as after the result has been verified. Hence, you should always reset your mock objects before each test so that you do not get any accidental mocking behavior.</p>
<p>As a side note, another solution would be to annotate the test class (or all of its test methods) with the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/annotation/DirtiesContext.html">@DirtiesContext</a> annotation. This will effectively recreate the entire application context after each test has been executed, causing all Spring beans to be in their initial state and thus the mock beans to be in the <i>record</i> state. Although this will work, there will be a significant performance penalty compared to the suggested <code>reset()</code> and <code>@Before</code> / <code>@After</code> solution, because all beans in the application context will be recreated and re-wired before each test method. </p>
<h2>Dependencies</h2>
<ul>
<li>Spring 3.0.6</li>
<li>Mockito 1.8.5</li>
<li>jUnit 4.10</li>
<li>EasyMock 3.1</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testing-ctx-management">Spring Reference Manual - Test Context Management and Caching</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testcontext-junit4-runner">Spring Reference Manual - SpringJunit4ClassRunner</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#integration-testing-annotations">Spring Reference Manual - ContextConfiguration</a></li>
<li><a href="http://easymock.org/EasyMock3_1_Documentation.html">EasyMock</a></li>
<li><a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html">Mockito</a></li>
</ul>
<p>Previous post: <a href="http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/">Spring Integration Tests, Part I, Creating Mock Objects</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Spring Integration Tests, Part I, Creating Mock Objects</title>
		<link>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/</link>
		<comments>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 20:26:05 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[factory-method]]></category>
		<category><![CDATA[factorybean]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10514</guid>
		<description><![CDATA[When writing integration tests with Spring, it can sometimes be convenient to mock one or more of Spring bean dependencies. However, during some circumstances strange things may happen... (In this post, Mockito has been used for creating mock objects, but the same problem applies to EasyMock as well. You can find the corresponding files if [...]]]></description>
			<content:encoded><![CDATA[<p>When writing integration tests with Spring, it can sometimes be convenient to mock one or more of Spring bean dependencies. However, during some circumstances strange things may happen...</p>
<p><small>(In this post, <a href="http://www.mockito.org">Mockito</a> has been used for creating mock objects, but the same problem applies to <a href="http://www.easymock.org">EasyMock</a> as well. You can find the corresponding files if you follow the provided links.)</small></p>
<h2>Test setup</h2>
<p>In the following example the <code>SomeClass</code> needs a reference to an instance of the <code>SomeDependency</code> interface:</p>
<p><script src="https://gist.github.com/1397610.js?file=SomeClass.java"></script></p>
<p><script src="https://gist.github.com/1397610.js?file=SomeDependency.java"></script></p>
<p>When writing the integration test, we use the static  <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class classToMock)</a> method to create a mock instance. The straightforward approach would be to let Spring instantiate the mock object with a <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method">static factory method</a> in the xml configuration, e.g.</p>
<p><script src="https://gist.github.com/1397610.js?file=failing-mockito-config.xml"></script><br />
<small>(Corresponding <a href="https://gist.github.com/1397610#file_failing_easymock_config.xml">EasyMock config</a>.)</small></p>
<p>To verify that the beans are created and wired correctly, we write a simple test:</p>
<p><script src="https://gist.github.com/1397610.js?file=BeanWiringTest.java"></script><br />
<small>(Same test for EasyMock, just update the <code>@ContextConfiguration</code> with the EasyMock config file.)</code></small></p>
<p>To our surprise, the test fails:</p>
<pre>
[...]
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'someClass': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private com.jayway.example.SomeDependency com.jayway.example.SomeClass.someDependency;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
    No matching bean of type [com.jayway.example.SomeDependency] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
[...]
</pre>
<h2>Explanation</h2>
<p>In order to find a solution to the problem, we need to understand Spring's initialization process:</p>
<ol>
<li>
<i>Load bean definitions.</i><br />
This step includes scanning the application context XML files, scanning packages defined by <code>component-scan</code>, and loading the bean definitions found into the bean factory. (BeanFactoryPostProcessors such as the PropertyPlaceHolderConfigurer may be called to update the bean definitions.)
</li>
<li>
<i>Instantiate beans and store them in the application context.</i><br />
The bean factory creates the bean from the bean definitions. Bean dependencies get injected.
</li>
<li>
<i>Bean post processing.</i><br />
All initializing methods (e.g. annotated with <code>@PostConstruct</code>, <code>init-method</code>s declared in the XML and the <code>afterPropertiesSet()</code> method will execute. Annotations such as <code>@Required</code> will be validated. Dynamic proxies in an AOP environment will be created and so on.
</li>
</ol>
<p>The problem that we see occurs due to a corner case in the first two steps. When the bean definition is created Spring scans through the application context XML file. It finds the declaration of the mock bean and a reflective call is made to find out the return type of the method defined by the <code>factory-method</code> declaration in an attempt to determine the bean's type. The return type of this method is declared as the formal type parameter <code>&lt;T&gt;</code> (remember that we use the <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class&lt;T&gt; classToMock)</a> as factory method). Consequently, the bean definition of <code>someDependencyMock</code> will be of <code>java.lang.Object</code> and not <code>SomeDependency</code> as one would think.</p>
<p>In the second step, the <code>someClass</code> bean is instantiated. Springs discovers the <code>@Autowired</code> annotation and tries to fetch an existing <code>SomeDependency</code> bean from the application context. None has yet been created, so the bean factory proceeds and looks for suitable bean definition in order to create an instance of the requested bean on the fly. This operation fails because the bean definition of <code>someDependency</code> is mapped to <code>java.lang.Object</code>. At this point, Spring bails out and throws the <code>NoSuchBeanDefinitionException</code>.  </p>
<h2>FactoryBean to the rescue</h2>
<p>The problem is solved by implementing a custom <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean">FactoryBean</a> that can be used whenever we need to mock an object:</p>
<p><script src="https://gist.github.com/1397610.js?file=MockitoFactoryBean.java"></script><br />
<small>(In the <a href="https://gist.github.com/1397610#file_easy_mock_factory_bean.java">EasyMockFactoryBean</a>, I have added an enum to define the type of mock object.)</small></p>
<p>Next, the Spring test config is updated to use the factory bean:</p>
<p><script src="https://gist.github.com/1397610.js?file=mockito-factory-bean.xml"></script><br />
<small>(Corresponding <a href="https://gist.github.com/1397610#file_easymock_factory_bean.xml">EasyMock config</a>.)</small></p>
<p>Spring will still instantiate the beans in the order that they were declared in the <code>mockito-test-config.xml</code>, i.e. starting by creating an instance of <code>SomeClass</code> and then attempt to inject an instance of a <code>SomeDependency</code> into it before any has been created. The good news is that bean factory will scan through all declared <code>FactoryBean</code>s, calls its <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/FactoryBean.html#getObjectType()">getObjectType()</a> method, and if the returned type is correct, call its <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/FactoryBean.html#getObject()">getObject()</a> which should return an instance of the requested type.</p>
<h2>Alternative solution</h2>
<p>There is another more brittle solution to the problem. By simply changing the order of the tags in the initial application context, e.g. putting the bean declaration that defines the mock above the component scan, will cause the test to pass. The bean definition will still be wrong in the sense that the <code>someDependencyMock</code> will be defined as a <code>java.lang.Object</code>, but there is another important difference. In this case, the bean factory will invoke the <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class&lt;T&gt; classToMock)</a> method with <code>SomeDependency</code> as parameter causing the <code>someDependencyMock</code> bean to be created and subsequently stored in the application context. Later, the <code>someClass</code> bean is created and the dependency can obtained from the application context when requested by the bean factory and the wiring of the beans will succeed. However, making sure that the order of the bean declarations in the XML is always correct may neither be simple nor obvious, and it will get increasingly more difficult the more beans you add to the configuration.</p>
<h2>Disclaimer</h2>
<p>As stated in the in the first paragraph, I would only consider this solution for <i>integration</i> tests because of performance reasons. The application context itself adds some overhead, but the big performance hit is to create and wire all beans that are associated with it. When writing <i>unit</i> tests there is no need for this, so you could revert to constructor or setter dependency injection, Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html#setField%28java.lang.Object,%20java.lang.String,%20java.lang.Object%29">ReflectionTestUtils.setField()</a>, PowerMock's <a href="http://powermock.googlecode.com/svn/docs/powermock-1.4.10/apidocs/org/powermock/reflect/Whitebox.html#setInternalState%28java.lang.Object,%20java.lang.Class,%20java.lang.Object%29">Whitebox.setInternalState()</a>, Mockito's <a href="http://docs.mockito.googlecode.com/hg/org/mockito/InjectMocks.html">@InjectMocks</a> or similar techniques.</p>
<h2>Acknowledgements</h2>
<p>Thanks to <a href="http://stackoverflow.com/users/97641/wilhelm-kleu">Wilhelm Kleu</a> at stack overflow for <a href="http://stackoverflow.com/questions/6340007/autowiring-of-beans-generated-by-easymock-factory-method/6340391#6340391">suggesting</a> the solution and to <a href="http://blog.jayway.com/author/mattiasarthursson/">Mattias Hellborg Arthursson</a> for valuable discussions.</p>
<h2>Dependencies</h2>
<ul>
<li>Spring 3.0.6</li>
<li>Mockito 1.8.5</li>
<li>jUnit 4.10</li>
<li>EasyMock 3.1</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method">Spring Reference Manual - Static Factory Method</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean">Spring Reference Manual - FactoryBean</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#integration-testing-annotations">Spring Reference Manual - Integration Testing</a></li>
<li><a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html">Mockito</a></li>
<li><a href="http://easymock.org/EasyMock3_1_Documentation.html">EasyMock</a></li>
</ul>
<p>Next post: <a href="http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/">Spring Integration Tests, Part II, Using Mock Objects</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Learn to Stop Worrying and Love the Singleton</title>
		<link>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/</link>
		<comments>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 13:00:10 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[spring ldap]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4273</guid>
		<description><![CDATA[Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. [...]]]></description>
			<content:encoded><![CDATA[<p>Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. This means that a mobile application must start in an instant, whereas starting and enterprise application may take as long as it takes. </p>
<p>Dependency injection and early validation is crucial for an enterprise application, and <a href="http://www.springsource.org/">Spring</a> is a boon in this regard. But do not fool yourself, Spring is good, but it is not a universal cure. Especially not in mobile space where startup times, low memory consumption, and avoiding interfaces are virtues.</p>
<p>The bottleneck in an enterprise application is most probably the database, spending a few extra milliseconds here and there seldom matters. On much less performant mobile device those clock cycles are not only time the user has to spend waiting, it will drain the battery. A simple thing as using an interface instead of an abstract superclass will perform at least twice as slow. Even passing an extra argument in the constructors a few nestings deep will have an impact.</p>
<h3>Lazy Singeltons by Choice</h3>
<p>Class loading in Java is lazy, the Java VM will not load classes until they are referenced. Odds are that the user will not trigger a full coverage of all classes in your app for a short time running mobile app. If the user just checks for incoming messages and quits, then every class involved in composing messages do not need to be loaded. Early dependency injection breaks this, as all classes will be referenced at startup. Most components will be initialized in vain, as they are never actually used.</p>
<p>So what we should do in mobile application is to work more like the Java VM, and less like Spring. If possible do not create a component until it is requested. The best way to do this is using a singleton pattern. Not a normal enforced singleton pattern, but rather a singleton by choice. Let the constructor be public, trust your users, and name the getter <code>getSharedFoo()</code>, not <code>getInstance()</code>. Let me show you using a example of an URL cache component:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  public URLCache() {
    // More code...
  }
  // Allot more code here...

}</pre>
<p>Using this shared URL cache component from our imaginary HTTP provider would then be super easy, but not mandatory:</p>
<pre class="brush:java">public class HTTPProvider {

  public InputStream inputStreamForURL(String url) {
    URLCache cache = URLCache.getSharedURLCache();
    // Use the cache...
  }

}</pre>
<p>The big win here is that if the code path of this run of the application never tries to open an input stream then the URL cache never has to be created. Saving several hundred milliseconds of reading cache indexes, validation, etc.</p>
<h3>But What About Testing?</h3>
<p>Are not singletons bad for unit tests and mocking components? They used to be. These days we have <a href="http://www.powermock.org/">PowerMock</a>, you really should use it. Turns out that not even PowerMock is really required, if we just change our singleton pattern very slightly, and allows the outside to set the shared component as well:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static void setSharedURLCache(URLCache cache) {
    synchronized (URLCache.class) {
      sharedCache = cache;
    }
  }

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  // Allot more code here...

}</pre>
<p>This small addition allows us for setup up our own mock cache in the setup of our unit tests. With something as simple as this:</p>
<pre class="brush:java">public class SomeTest extends TestCase {

  public void setUp() {
    URLCache.setSharedURLCache(new NoOpURLCache());
  }

  public void testRemoteResource() {
    assertNotNull(HTTPProvider.getSharedHTTPProvider().inputStreamForURL(TEST_URL));
  }
}</pre>
<p>It also allows us for explicitly override a singleton if our application has special needs, perhaps a more aggressive cache on a low bandwidth mobile data connection, or special implementation on a buggy Java ME platform. But most importantly for the normal case it will not waste time creating the component until it is actually needed, vastly improving the user experience for your mobile users.</p>
<h3>Take Aways</h3>
<p>Do not fear singletons, it is a great way of lazy creations that will greatly improve startup times and memory consumption on mobile applications.</p>
<p>Avoid using interfaces, they are at least twice as slow as classes, and can not have static methods for acquiring the lazy created components.</p>
<p>Do not enforce the singleton pattern, always use singleton by choice. To allow for testing and easy implementation of special cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Getting started with JavaME jUnit testing</title>
		<link>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/</link>
		<comments>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 14:36:36 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1191</guid>
		<description><![CDATA[Introduction Unit testing is a very powerful tool that should be included in every developer's toolbox. Unfortunately, this has not always been the case, especially not among MIDlet developers. One reason is that JavaME projects usually are small (compared to Java SE projects), which implies that manual testing could be enough. However, as soon as [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Unit testing is a very powerful tool that should be included in every developer's toolbox. Unfortunately, this has not always been the case, especially not among MIDlet developers. One reason is that JavaME projects usually are small (compared to Java SE projects), which implies that manual testing could be enough. However, as soon as you start developing production code you really should consider to automate your tests by developing your own test suite. </p>
<p>Some of you may have played around with <a href="http://sourceforge.net/projects/jmunit">JMUnit</a> project. It is a nice framework that allows you to write tests that can be transferred to your phone or emulator and you will see the test result on the display. Alternatively, the tests can be executed by Ant. Still, there are some limitations that you cannot bypass:</p>
<ul>
<li>Because of CLDC's lack of reflection, you cannot benefit from the powers of <a href="http://www.junit.org/">jUnit 4.x</a>.</li>
<li>You cannot create mock objects. This means that if a class has dependencies to other classes you will perform an integration test rather than a <i>unit</i> test.</li>
<li>The turn around time for test, debug and retest, is significantly larger compared to Java SE unit testing, especially if you are executing the test on the phone.</li>
</ul>
<p>No offence to the JMUnit guys, they are restricted by the limitations of the CLDC VM and the fact that you need a target device (a phone or an emulator) to run the tests on. But maybe there is a workaround to solve these problems? With some tricks, it is possible to unit test your JavaME code in the same way as you would unit test your Java SE code. In other words, you can execute the tests <i>on the PC side without deploying the tests to an emulator or a phone</i>. </p>
<h3>PowerMock</h3>
<p>One part of the solution is to mock any platform dependencies. Previously, it was an awkward job to do, but the introduction of  <a href="http://code.google.com/p/powermock/">PowerMock</a> allows us to mock the many static methods in MIDP and CLDC. The easiest way to get started with powermock is to download the <a href="http://code.google.com/p/powermock/downloads/list">powermock-1.2-with-dependencies.zip</a>. In another <a href="http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/">post</a> I have explained how PowerMock can be used to mock the RecordStore in MIDP.</p>
<h3>Project configuration</h3>
<p>If you are using Eclipse, you need two projects, one for your phone application and the other your test code. This is because different projects can have different java compiler settings.</p>
<ul>
<li>Create a <i>MIDlet</i> project. This is your phone application. Make sure that the "Java Compiler" compliance level is "1.3".</li>
<li>Create a <i>Java</i> project. This is the test project where you will write your tests. Make sure that the "Java Compiler" compliance level is set to "1.6" (or to whatever JDK version you have installed).
<ul>
<li>Add the midlet project you just created to "Required projects" in the "Java Build Path" setting.</li>
<li>Add the PowerMock jar files and their dependencies to "Libraries" in the "Java Build Path" setting.</li>
</ul>
</ul>
<p>In the MIDlet project, you write your application code and in the java test project you write your java jUnit tests. Normal package protection rules apply, so you should consider to reuse the package name from the class in the midlet project you would like to test when you are writing the test class in the java project.</p>
<h3>Automation</h3>
<p>Naturally, it is possible to automate the test by using build tools. Here is an example using of an Ant build.xml file:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="font-weight: bold; color: black;">?&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;project</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Example&quot;</span> <span style="color: #000066;">default</span>=<span style="color: #ff0000;">&quot;test&quot;</span> <span style="color: #000066;">basedir</span>=<span style="color: #ff0000;">&quot;.&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;midlet.project.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_workspace/MidletProject&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.project.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_workspace/MidletProjectTest&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;powermock.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_path/powermock-1.2&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;wtk.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/WTK2.5.2&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;src.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${midlet.project.home}/src&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.src.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${test.project.home}/src&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;bin.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;classes&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.bin.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;test-classes&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.result.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;test-result&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${wtk.home}/lib&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;include</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;*.jar&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/fileset<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/path<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;pathelement</span> <span style="color: #000066;">location</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${powermock.home}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/path<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;clean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;compile&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;javac</span> <span style="color: #000066;">srcdir</span>=<span style="color: #ff0000;">&quot;${src.dir}&quot;</span>
			<span style="color: #000066;">destdir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span>
			<span style="color: #000066;">source</span>=<span style="color: #ff0000;">&quot;1.3&quot;</span>
			<span style="color: #000066;">target</span>=<span style="color: #ff0000;">&quot;1.1&quot;</span>
			<span style="color: #000066;">classpathref</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;compile-tests&quot;</span> <span style="color: #000066;">depends</span>=<span style="color: #ff0000;">&quot;compile&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;javac</span> <span style="color: #000066;">srcdir</span>=<span style="color: #ff0000;">&quot;${test.src.dir}&quot;</span>
			<span style="color: #000066;">destdir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span>
			<span style="color: #000066;">classpathref</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test&quot;</span> <span style="color: #000066;">depends</span>=<span style="color: #ff0000;">&quot;clean, compile-tests&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;junit</span> <span style="color: #000066;">printsummary</span>=<span style="color: #ff0000;">&quot;yes&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;classpath</span> <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;classpath</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;formatter</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;plain&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;batchtest</span> <span style="color: #000066;">fork</span>=<span style="color: #ff0000;">&quot;yes&quot;</span> <span style="color: #000066;">todir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
				<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.src.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/batchtest<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/junit<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/project<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now your project configuration is setup and you can test your MIDlet code in the same way as you would test your Java SE code. </p>
<h3>What's next?</h3>
<p>If you are a dedicated MIDlet developer you would probably like to add more build targets later on to preverify, obfuscate, sign, package and deploy your MIDlet. </p>
<p>You should also consider using a continuous integration server together with your version control system and configure it to run your test suite whenever the code has been changed. Depending on the server you choose, you may also find that it may be used to present result from static code analysis tools, code coverage, code metrics and so on.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to mock MIDP RecordStore</title>
		<link>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/</link>
		<comments>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 14:32:32 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1229</guid>
		<description><![CDATA[The challenge PowerMock is a mocking framework that claims to have almost supernatural powers. According to its documentation it is able to mock both static and private methods, final classes, and other nasty things that would be insurmountable obstacles for other mock frameworks. As a result, it has been stated that it should be able [...]]]></description>
			<content:encoded><![CDATA[<h3>The challenge</h3>
<p>PowerMock is a mocking framework that claims to have almost supernatural powers. According to its documentation it is able to mock both static and private methods, final classes, and other nasty things that would be insurmountable obstacles for other mock frameworks. As a result, it has been stated that it should be able to mock the MIDP RecordStore, but so far I have not seen a working example. I accepted the challenge.</p>
<h3>Getting started</h3>
<p>I decided that writing a unit test was the best way to get started. After all, mocking is usually used together with unit testing.<br />
In order to use RecordStore you must first open it. According to the <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/rms/RecordStore.html">javadoc of RecordStore</a>, the method to be used is: <code>public static RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary)</code>.<br />
A static method that returns an instance of the RecordStore object. Following the "Mocking static methods" guidelines on the <a href="http://code.google.com/p/powermock/">PowerMock web site</a>, it seemed to be a pretty straight forward task:</p>
<ol>
<li>Use the <code>@RunWith</code> annotation at the class-level of the test case.</li>
<li>Use the <code>@PrepareForTest</code> annotation at the class-level of the test case.</li>
<li>Use <code>PowerMock.mockStatic()</code> to mock all methods of this class.</li>
<li>Use <code>PowerMock.replay()</code> to change the class to replay mode.</li>
<li>Use <code>PowerMock.verify()</code> to change the class to verify mode.</li>
</ol>
<p>Ok, a little more complicated than my ordinary EasyMock setup, but nothing to really worry about. In my case, I also needed to create a mock object of the RecordStore class itself because of the return value of the <code>openRecordStore()</code> method. </p>
<h3>The setback</h3>
<p>To my disappointment, my test failed with an <code>ExceptionInInitializerError</code>. I studied the code thoroughly to make sure that I had followed the instructions, but I concluded that error resided elsewhere. A closer look at the failure trace revealed:<br />
<code><br />
[...]<br />
Caused by: java.lang.UnsupportedOperationException: getSlowingFactor is native<br />
at javax.microedition.rms.RecordStore.getSlowingFactor(RecordStore.java)<br />
at javax.microedition.rms.RecordStore.<clinit>(RecordStore.java:2414)<br />
[...]<br />
</code><br />
Hmm, that is strange... According to the API, there should be no <code>getSlowingFactor()</code> in RecordStore? And it seems like it is called by the class initializer? When searching for an answer it seemed like this problem occurs if you have not configured the preverifier correctly. It sort of makes sense, I am not using a preverifier at all in my project and I did not like the idea of introducing one. </p>
<h3>The solution</h3>
<p>Returning to the PowerMock documentation, I discovered instructions how to "Suppressing Unwanted Behavior", maybe this was the way forward? Soon, I found the annotation <code>@SuppressStaticInitializationFor</code>, I added it to my test case and voilÃ , I had successfully mocked the RecordStore!</p>
<h3>Reference code</h3>
<p>You can find the code needed to mock the RecordStore below. If you find it interesting, you can <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/example.zip'>download</a> a more complex example where a class that uses RecordStore for persistent storage is unit tested with aid of PowerMock.</p>
<pre class="java">&nbsp;
<span style="color: #a1a100;">import static org.easymock.EasyMock.expect;</span>
<span style="color: #a1a100;">import static org.easymock.classextension.EasyMock.createMock;</span>
<span style="color: #a1a100;">import static org.junit.Assert.assertEquals;</span>
<span style="color: #a1a100;">import javax.microedition.rms.RecordStore;</span>
<span style="color: #a1a100;">import javax.microedition.rms.RecordStoreException;</span>
&nbsp;
<span style="color: #a1a100;">import org.junit.Test;</span>
<span style="color: #a1a100;">import org.junit.runner.RunWith;</span>
<span style="color: #a1a100;">import org.powermock.api.easymock.PowerMock;</span>
<span style="color: #a1a100;">import org.powermock.core.classloader.annotations.PrepareForTest;</span>
<span style="color: #a1a100;">import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;</span>
<span style="color: #a1a100;">import org.powermock.modules.junit4.PowerMockRunner;</span>
&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>PowerMockRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@SuppressStaticInitializationFor<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;javax.microedition.rms.RecordStore&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> RecordStoreMockTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testCreateRecordStoreMock<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> RecordStoreException <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> recordStoreName = <span style="color: #ff0000;">&quot;record_store_name&quot;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Create mocks</span>
		PowerMock.<span style="color: #006600;">mockStatic</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		RecordStore recordStoreMock = createMock<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Record behavior</span>
		expect<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #006600;">openRecordStore</span><span style="color: #66cc66;">&#40;</span>recordStoreName, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>
				recordStoreMock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Replay behavior</span>
		PowerMock.<span style="color: #006600;">replay</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Execute test and verify result</span>
		assertEquals<span style="color: #66cc66;">&#40;</span>recordStoreMock, RecordStore.<span style="color: #006600;">openRecordStore</span><span style="color: #66cc66;">&#40;</span>recordStoreName, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		PowerMock.<span style="color: #006600;">verify</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mocking Eclipse IResource.accept()</title>
		<link>http://blog.jayway.com/2009/01/15/mocking-eclipse-iresourceaccept/</link>
		<comments>http://blog.jayway.com/2009/01/15/mocking-eclipse-iresourceaccept/#comments</comments>
		<pubDate>Thu, 15 Jan 2009 08:39:48 +0000</pubDate>
		<dc:creator>Tobias Södergren</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=761</guid>
		<description><![CDATA[I had a junit test situation where I wanted to mock an Eclipse IResource instance but still be able to test a call-back implementation given as parameter to the mocked IResource.accept(IResourceVisitor visit) method. By default, mocking an interface gives you "call count" and expected return values but no code is executed. In order to test the implementation of IResourceVisitor, something more had to be done. Here is how I did it.]]></description>
			<content:encoded><![CDATA[<p>I am currently involved in making the ClearCase plug-in for Eclipse, the one hosted at SourceForge, a bit better. Part of the job consists of creating unit tests to make sure that my fixes will stay fixed.</p>
<p>One interesting problem was that in some of my tests, I had to mock the <code>org.eclipse.core.resources.IResource</code> interface. Nothing too hard about that, just write the following code, using EasyMock 2.4:</p>
<pre class="java">&nbsp;
@Override
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setUp<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">setUp</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   resource1 = createMock<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;resource1&quot;</span>, IResource.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
   resource2 = createMock<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;resource2&quot;</span>, IResource.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now to my problem. First, I will discuss what the IResource.accept(IResourceVisitor visitor) metod does:<br />
The IResource.accept(...) method traverses the directory structure under the resource. For each resource found, starting with the IResource on which accept() was called, the visitor.visit(IResource resource) method is called. If the visit(...) method returns true, the directory structure under the resource is traversed, otherwise traversing stops for that specific resource. This way parts of the directory structure under an IResource can be visited.</p>
<p>The problem I encountered was that since I have an IResource mock, there is no code for the accept() method. The mock will just register that there has been a call for accept(), but the code in the IResourceVisitor.visit(IResource resource), which I want tested, is never called.</p>
<p>What to do? There are different solutions, one example is to use an implementation of IResource, for example <code>org.eclipse.core.internal.resources.Folder</code>, and create a partially mocked object and keep the code for accept(). Not a nice solution though, my test would depend on internal code in the Eclipse project. What I did instead was to use the <code>org.easymock.EasyMock.expectLastCall().andAnswer(IAnswer answer)</code> functionality. The andAnswer() method takes an IAnswer callback implementation, like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testCollectRefreshStatus<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> CoreException <span style="color: #66cc66;">&#123;</span>
   <span style="color: #808080; font-style: italic;">// Normal mock expects</span>
   expect<span style="color: #66cc66;">&#40;</span>resource1.<span style="color: #006600;">getLocation</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>iPath1<span style="color: #66cc66;">&#41;</span>;
   expect<span style="color: #66cc66;">&#40;</span>iPath1.<span style="color: #006600;">toOSString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>RESOURCE_PATH_1<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">times</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #808080; font-style: italic;">// Provide code for accept(...)</span>
   resource1.<span style="color: #006600;">accept</span><span style="color: #66cc66;">&#40;</span>isA<span style="color: #66cc66;">&#40;</span>IResourceVisitor.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
   expectLastCall<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andAnswer</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> IAnswer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> answer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span> <span style="color: #808080; font-style: italic;">// 1.</span>
        IResourceVisitor visitor = <span style="color: #66cc66;">&#40;</span>IResourceVisitor<span style="color: #66cc66;">&#41;</span> EasyMock.<span style="color: #006600;">getCurrentArguments</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>; <span style="color: #808080; font-style: italic;">// 2.</span>
        visitor.<span style="color: #006600;">visit</span><span style="color: #66cc66;">&#40;</span>resource2<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// 3.</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">null</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
   expect<span style="color: #66cc66;">&#40;</span>resource2.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file.txt&quot;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// 4.</span>
&nbsp;
   replayMocks<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #808080; font-style: italic;">// Perform test</span>
   myTestTarget.<span style="color: #006600;">someMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   <span style="color: #808080; font-style: italic;">// Verify test</span>
   assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, myTestTarget.<span style="color: #006600;">getNumberOfResources</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
   verifyMocks<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Here are some comments to the marked lines in the code above:</p>
<p>1. The answer() method is dictated by the IAnswer interface.<br />
2. EasyMock provides a method to get access to the objects sent as parameters for the expected call. In this case, the call is resource1.accept(...) and the parameter is the IResourceVisitor implementation defined in myTestTarget, which is the code that should be tested.<br />
3. Here the test code has control of the call to the IResourceVisitor.visit() and a mock IResource is provided as parameter. To make the test even better, the boolean return value from the visit() call should be saved and asserted for the correct value to ensure that the intended traversing works as expected.<br />
4. Here the expectations on the mock IResource, for the visit(IResource ...) call, is defined. In this case myTestTarget calls getName() on IResource for some reason, so expectations for that is defined together with a resulting return value that would steer the logic in some direction.</p>
<p>This way the test has full control of the visitor implementation and it is fairly easy to test all the criterias that makes the IResourceVisitor.visit(...) implementation return true or false. Also, the visit() method often changes state of something else, and here it is also possible to test that the state is changed correctly by simulating multiple visit(...) calls, by adding more calls to visit at 3. in the code above. </p>
<p>/Tobias S&ouml;dergren</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/01/15/mocking-eclipse-iresourceaccept/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerMock 1.0 released</title>
		<link>http://blog.jayway.com/2008/11/21/powermock-10-released/</link>
		<comments>http://blog.jayway.com/2008/11/21/powermock-10-released/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 20:54:42 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[oredev]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=456</guid>
		<description><![CDATA[We have released 1.0 of PowerMock just in time for the Øredev conference! PowerMock is an open source mock framework based on EasyMock that allow you to mock static methods, private methods and even constructors. Our intent is mainly to allow unit testing of legacy code and people really seemed to appreciate this idea at the conference.]]></description>
			<content:encoded><![CDATA[<p>We have released 1.0 of <a href="http://www.powermock.org">PowerMock</a> just in time for the <a href="http://www.oredev.org/">Øredev</a> conference! PowerMock is an open source mock framework based on <a href="http://www.easymock.org/">EasyMock</a> that allow you to mock static methods, private methods and even constructors. Our intent is mainly to allow unit testing of legacy code and people really seemed to appreciate this idea at the conference.</p>
<p>We now think that the API is stable enough and we have also tested PowerMock in a couple of projects, but of course since we were presenting at the conference it is no coincidence that we released PowerMock 1.0 just days before. <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>The details of the changes can be found in the <a href="http://powermock.googlecode.com/svn/trunk/changelog.txt">changelog</a> but here are some of the highlights since <a href="http://blog.jayway.com/2008/10/27/powermock-08-released/">PowerMock 0.8</a>:</p>
<ul>
<li>The ability to <a href="http://code.google.com/p/powermock/wiki/BypassEncapsulation">set and get internal state</a> based on an object type. This means that you get more refactor friendly code while still being able to set internal state. </li>
<li>Implemented <a href="http://code.google.com/p/powermock/wiki/ReplayAllAndVerifyAll">replayAll and verifyAll</a>. These can be used to replay and verify all mocks created by PowerMock without having to explicitly specify each and everyone. Thanks to <a href="http://www.agilejava.eu/">Ivar Grimstad</a> for suggesting this!</li>
<li>Added support for specifying parameter types for expectNew. <a href="http://code.google.com/p/powermock/wiki/MockConstructor">Mocking constructor calls</a> is a unique feature of PowerMock that people typically find very cool!</li>
</ul>
<p>During the conference I talked to several people and got really good feedback. Everybody seemed to like the idea of being able to unit test legacy code and code that haven't been designed for testing. <a href="http://www.two-sdg.demon.co.uk/curbralan/kevlin.html">Kevlin Henney</a> made a good job of <a href="http://www.oredev.org/topmenu/program/tracktest/kevlinhenney.4.3efb083311ac562f9fe800011931.html">defining and describing various types of unit testing</a> during his talk at Øredev and we talked about the difference between essentially untestable code and accidentally untestable code. PowerMock solves the problem with code being untestable for technical reasons (part of the accidentally untestable). With all the great sessions and good discussions Øredev was yet again a great experience!</p>
<p>I have made <a href="http://powermock.googlecode.com/files/PowerMockAtOredev.pdf">the slides from the presentation</a> available at <a href="http://powermock.org">powermock.org</a>. Note that the demo we showed was actually from the trunk and not from the 1.0 release!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/21/powermock-10-released/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerMock 0.8 released</title>
		<link>http://blog.jayway.com/2008/10/27/powermock-08-released/</link>
		<comments>http://blog.jayway.com/2008/10/27/powermock-08-released/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 20:37:33 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=371</guid>
		<description><![CDATA[Previously a colleague of mine described an idea for mocking static methods. Earlier this year we started an open source project to implement these ideas in a very simple to use form. The idea is that it will just be a normal jar file that extends EasyMock and JUnit. Instead of using AspectJ we have [...]]]></description>
			<content:encoded><![CDATA[<p>Previously a colleague of mine described an idea for <a href="http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/">mocking static methods</a>. Earlier this year we started an open source project to implement these ideas in a very simple to use form. The idea is that it will just be a normal jar file that extends EasyMock and JUnit. Instead of using AspectJ we have created our own classloader which means that you don't have to make changes to your build environment. <a href="http://www.powermock.org">PowerMock</a>, as the project is called,  is mostly intended for whitebox unit testing where you know what is going on inside a class or method that you want to test. There is even a class called Whitebox which can be used for simple access to private methods and fields. Besides static mocking we have many other interesting features such as mocking constructors, final classes and methods, private methods, removal of static initializers etc.</p>
<p>We have received some feedback and have also started some evaluation in one of our customer's project. Besides bug-fixes and documentation updates we are starting to stabilize the API and preparing for the 1.0 release. We are also <a href="http://www.oredev.org/topmenu/program/trackjava/johanhalebyjankronqvist.4.3efb083311ac562f9fe80009168.html">presenting PowerMock</a> at this years <a href="http://www.oredev.org/">Øredev</a> conference. You're more than welcome to try it out for yourself.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/27/powermock-08-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mocking Classes</title>
		<link>http://blog.jayway.com/2007/05/09/mocking-classes/</link>
		<comments>http://blog.jayway.com/2007/05/09/mocking-classes/#comments</comments>
		<pubDate>Wed, 09 May 2007 14:31:34 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=165</guid>
		<description><![CDATA[Mocking a class rather than an interface might present some interesting obstacles. Perhaps you have ran into the dreaded: Unexpected method call toString(): toString(): expected: 0, actual: 1 You think nothing of it and happily add an expectation for toString. Then you get: Unexpected method call toString(): toString(): expected: 1, actual: 2 The reason is [...]]]></description>
			<content:encoded><![CDATA[<p>Mocking a class rather than an interface might present some interesting obstacles. Perhaps you have ran into the dreaded:</p>
<pre>Unexpected method call toString():
  toString(): expected: 0, actual: 1</pre>
<p>You think nothing of it and happily add an expectation for toString. Then you get:</p>
<pre>Unexpected method call toString():
  toString(): expected: 1, actual: 2</pre>
<p>The reason is that EasyMock itself calls <tt>toString</tt> for each expectation, so it's a never-ending story. However, it appears only when your class under test has overridden any (or all) of <tt>toString</tt>, <tt>equals</tt> or <tt>hashCode</tt>. There is a way around it. You can tell EasyMock's <tt>MockClassControl</tt> which methods you want it to mock. Yes, you heard it right: "which methods you <em>want it</em> to mock". I know, you'd rather want to tell it which methods you <em>don't</em> want it to mock, like <tt>toString</tt>, <tt>equals</tt> and <tt>hashCode</tt>.</p>
<p>I'll show you a couple of utility classes that let you do that. We ran into this problem in a previous project and wrote the classes below. They let you get away with this neat code that should be used whenever you mock a class:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyClassTest <span style="color: #000000; font-weight: bold;">extends</span> TestCase <span style="color: #66cc66;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">private</span> MockControl myClassControl;
   <span style="color: #000000; font-weight: bold;">private</span> MyClass myClassMock;
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setUp<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
      myClassControl = TestUtils.<span style="color: #006600;">createClassControl</span><span style="color: #66cc66;">&#40;</span>MyClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
      myClassMock = <span style="color: #66cc66;">&#40;</span>MyClass<span style="color: #66cc66;">&#41;</span> myClassControl.<span style="color: #006600;">getMock</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
   ...
<span style="color: #66cc66;">&#125;</span></pre>
<p>Here are the classes:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">testutils</span>; 
&nbsp;
<span style="color: #a1a100;">import org.easymock.MockControl; </span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Various utility functions for testing.
 *
 * @author Adam Skogman
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">class</span> TestUtils <span style="color: #66cc66;">&#123;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> TestUtils<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get a MockClassControl for the supplied class, using the first found
     * public or protected constructor and not mocking the toString(), equals()
     * and hashCode() methods.
     *
     * @param cls
     *            the class to create a MockClassControl for.
     * @return a MockClassControl for the class.
     * @see MockClassControlHelper
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> MockControl getMockClassControl<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> getMockClassControl<span style="color: #66cc66;">&#40;</span>
                cls,
                MockClassControlHelper.<span style="color: #006600;">DONT_MOCK_STD_METHODS</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get a MockClassControl for the supplied class, using the first found
     * public or protected constructor. If mockStdMethods is false, the
     * toString(), equals() and hashCode() methods will not be mocked.
     *
     * @param cls
     *            the class to create a MockClassControl for.
     * @param mockStdMethods
     *            whether toString(), equals() and hashCode() will be mocked.
     * @return a MockClassControl for the class.
     * @see MockClassControlHelper
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> MockControl getMockClassControl<span style="color: #66cc66;">&#40;</span>
            <span style="color: #000000; font-weight: bold;">Class</span> cls,
            <span style="color: #993333;">boolean</span> mockStdMethods<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        MockClassControlHelper helper = <span style="color: #000000; font-weight: bold;">new</span> MockClassControlHelper<span style="color: #66cc66;">&#40;</span>
                mockStdMethods<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> helper.<span style="color: #006600;">getMockClassControl</span><span style="color: #66cc66;">&#40;</span>cls<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">testutils</span>; 
&nbsp;
<span style="color: #a1a100;">import java.lang.reflect.Constructor;</span>
<span style="color: #a1a100;">import java.lang.reflect.Method;</span>
<span style="color: #a1a100;">import java.lang.reflect.Modifier;</span>
<span style="color: #a1a100;">import java.util.Arrays;</span>
<span style="color: #a1a100;">import java.util.Collection;</span>
<span style="color: #a1a100;">import java.util.HashSet;</span>
<span style="color: #a1a100;">import java.util.Set; </span>
&nbsp;
<span style="color: #a1a100;">import org.apache.commons.logging.Log;</span>
<span style="color: #a1a100;">import org.apache.commons.logging.LogFactory;</span>
<span style="color: #a1a100;">import org.easymock.MockControl;</span>
<span style="color: #a1a100;">import org.easymock.classextension.MockClassControl; </span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Helper class to easily create mock class controls.
 *
 * EasyMockClassExtension v1.1 has a couple of undocumented 'features' which are
 * rather annoying.
 *
 * First of all, if the class we want to mock does not have any public
 * constructor, it is not possible to do
 * MockClassControl.createControl(MyClass.class), since the search for
 * constructors is limited to 'public' access modifier if class and parameter
 * values are not specified.
 *
 * Secondly, if toString(), equals() or hashCode() is overridden in the class we
 * want to mock, parameter matching on the resulting mock will not work, since
 * the above methods will be mocked by default, causing mock control validation
 * to fail.
 *
 * As a solution this helper class will by default instruct MockClassControl not
 * to mock toString(), equals() and hashCode() (alternatively any methods
 * specified by a call to setStdMethods()).
 *
 * Methods in Object will not be mocked.
 *
 * @author Mattias Arthursson
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MockClassControlHelper <span style="color: #66cc66;">&#123;</span>
    Log log = LogFactory.<span style="color: #006600;">getLog</span><span style="color: #66cc66;">&#40;</span>MockClassControlHelper.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Indicates that standard methods will be mocked.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">boolean</span> MOCK_STD_METHODS = <span style="color: #000000; font-weight: bold;">true</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Indicates that standard methods will be mocked.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">boolean</span> DONT_MOCK_STD_METHODS = <span style="color: #000000; font-weight: bold;">false</span>; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">boolean</span> mockStdMethods; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collection</span></a> stdMethods; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Initialize to not mock standard methods.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> MockClassControlHelper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#40;</span>DONT_MOCK_STD_METHODS<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Initialize to mock standard methods depending on supplied parameter.
     *
     * @param mockStdMethods
     *            whether standard methods should be mocked.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> MockClassControlHelper<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">boolean</span> mockStdMethods<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">mockStdMethods</span> = mockStdMethods;
        stdMethods = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AArrays+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Arrays</span></a>.<span style="color: #006600;">asList</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #ff0000;">&quot;toString&quot;</span>, <span style="color: #ff0000;">&quot;equals&quot;</span>,
                <span style="color: #ff0000;">&quot;hashCode&quot;</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get a MockClassControl for the supplied class using the first found
     * public or protected constructor. Standard methods will be mocked
     * depending on mockStdMethods.
     *
     * @param cls
     *            the class to mock.
     * @return a MockClassControl for the supplied class.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> MockControl getMockClassControl<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AConstructor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Constructor</span></a> constructorToUse = getConstructorToUse<span style="color: #66cc66;">&#40;</span>cls<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
        <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> parameters = constructorToUse.<span style="color: #006600;">getParameterTypes</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> values = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a><span style="color: #66cc66;">&#91;</span>parameters.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#93;</span>; 
&nbsp;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> methodsToMock = getMethodsToMock<span style="color: #66cc66;">&#40;</span>cls<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> MockClassControl.<span style="color: #006600;">createControl</span><span style="color: #66cc66;">&#40;</span>
                cls,
                parameters,
                values,
                methodsToMock<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Set the standard methods to omit if mockStdMethods is set to false
     * (default).
     *
     * @param methods
     *            Names of the methods to omit when mocking.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setStdMethods<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> methods<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        stdMethods = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AArrays+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Arrays</span></a>.<span style="color: #006600;">asList</span><span style="color: #66cc66;">&#40;</span>methods<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Set the standard methods to omit if mockStdMethods is set to false
     * (default).
     *
     * @param c
     *            Collection of names of the methods to omit when mocking.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setStdMethods<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collection</span></a> c<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        stdMethods = c;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get the methods that will not be mocked.
     *
     * @return A collection of method names.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collection</span></a> getStdMethods<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> stdMethods;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Find a constructor to use. If public constructors are found, the first of
     * these is selected. Otherwise we check for a protected constructor, and
     * the first of these is used.
     *
     * @param cls
     *            Class to select a constructor from.
     * @return a public or protected constructor for the class.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AConstructor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Constructor</span></a> getConstructorToUse<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AConstructor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Constructor</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> constructors = cls.<span style="color: #006600;">getConstructors</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>constructors.<span style="color: #006600;">length</span> == <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #808080; font-style: italic;">// No public constructors found.</span>
            constructors = cls.<span style="color: #006600;">getDeclaredConstructors</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>constructors.<span style="color: #006600;">length</span> == <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalArgumentException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalArgumentException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Class '&quot;</span> + cls
                        + <span style="color: #ff0000;">&quot;' does not have any constructors&quot;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span> 
&nbsp;
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>; i &amp;lt; constructors.<span style="color: #006600;">length</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #993333;">int</span> modifiers = constructors<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">getModifiers</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AModifier+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Modifier</span></a>.<span style="color: #006600;">isPublic</span><span style="color: #66cc66;">&#40;</span>modifiers<span style="color: #66cc66;">&#41;</span> || <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AModifier+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Modifier</span></a>.<span style="color: #006600;">isProtected</span><span style="color: #66cc66;">&#40;</span>modifiers<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
                <span style="color: #808080; font-style: italic;">// We've found a constructor which is public or</span>
                <span style="color: #808080; font-style: italic;">// protected - use that one.</span>
                <span style="color: #000000; font-weight: bold;">return</span> constructors<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span> 
&nbsp;
        <span style="color: #808080; font-style: italic;">// No public or protected constructor found.</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalArgumentException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalArgumentException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Class '&quot;</span> + cls
                + <span style="color: #ff0000;">&quot;' does not have any public or protected constructors&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Figure out which methods of the class to mock. If mockStdMethods is set
     * to false, the standard methods are subtracted from all found methods for
     * the class. Otherwise all methods for the class is returned.
     *
     * @param cls
     *            The class to get methods for.
     * @return The methods to mock for the class.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> getMethodsToMock<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
        <span style="color: #000000; font-weight: bold;">Class</span> currentClass = cls;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASet+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Set</span></a> methods = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AHashSet+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">HashSet</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
        <span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>currentClass != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> methodArray = currentClass.<span style="color: #006600;">getDeclaredMethods</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
            <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>; i &amp;lt; methodArray.<span style="color: #006600;">length</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a> method = methodArray<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>;
                <span style="color: #993333;">boolean</span> isStandardMethod = stdMethods.<span style="color: #006600;">contains</span><span style="color: #66cc66;">&#40;</span>method
                        .<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
                <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>mockStdMethods || !isStandardMethod<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                    methods.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#41;</span>;
                <span style="color: #66cc66;">&#125;</span> 
&nbsp;
                <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>method.<span style="color: #006600;">getModifiers</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &amp;amp; <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AModifier+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Modifier</span></a>.<span style="color: #000000; font-weight: bold;">FINAL</span><span style="color: #66cc66;">&#41;</span> &amp;gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                    log.<span style="color: #006600;">warn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Final method, cannot be mocked: &quot;</span> + method<span style="color: #66cc66;">&#41;</span>;
                <span style="color: #66cc66;">&#125;</span>
            <span style="color: #66cc66;">&#125;</span> 
&nbsp;
            currentClass = currentClass.<span style="color: #006600;">getSuperclass</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentClass == <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                currentClass = <span style="color: #000000; font-weight: bold;">null</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span> 
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> methods.<span style="color: #006600;">toArray</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span>methods.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/05/09/mocking-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Static Mock using AspectJ</title>
		<link>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/</link>
		<comments>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/#comments</comments>
		<pubDate>Fri, 16 Feb 2007 09:00:08 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=284</guid>
		<description><![CDATA[After seeing <a href="http://mockme.org/">MockME</a> developed by some of my colleagues I started thinking about how this could be made in a generic way.]]></description>
			<content:encoded><![CDATA[<p>After seeing <a href="http://mockme.org/">MockME</a> developed by some of my colleagues I started thinking about how this could be made in a generic way. For example how would we mock the following class?</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StupidSingleton <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> doStatic<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AUnsupportedOperationException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">UnsupportedOperationException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;method not implemented yet...&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #993333;">void</span> sayHello<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Hello&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">void</span> nativeMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>We would like to write something like this:</p>
<pre class="java">&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testMocking<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mock<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		expect<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #006600;">doStatic</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">17</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;17&quot;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">sayHello</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">nativeMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		replay<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;17&quot;</span>, StupidSingleton.<span style="color: #006600;">doStatic</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">17</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">sayHello</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">nativeMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verify<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>After playing around with <a href="http://www.eclipse.org/aspectj/">AspectJ</a> I discovered that this is actually possible! Two things are needed:<br />
* An aspect that allows us to catch calls to static methods!<br />
* An implementation of the mock, replay, verify for classes</p>
<p>This turns out to be really easy! The following aspect catches ALL calls to ALL static methods. Might be a bit aggressive, but it works! If you want you can implement your own aspect with a more specialized pointcut.</p>
<pre class="java">&nbsp;
@Aspect
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMockAll <span style="color: #000000; font-weight: bold;">extends</span> StaticMockAspect <span style="color: #66cc66;">&#123;</span>
	@Pointcut<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;call(static * *(..))&quot;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> anyStaticOperation<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
&nbsp;
	@Around<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;anyStaticOperation()&quot;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> aroundStaticMethods<span style="color: #66cc66;">&#40;</span>ProceedingJoinPoint jp<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">aroundStaticMethods</span><span style="color: #66cc66;">&#40;</span>jp<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The mock, replay, verify methods turns out to be trivial:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMock <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">static</span> Map&lt;Class, MockInvocationHandler&gt; mocks = <span style="color: #000000; font-weight: bold;">new</span> HashMap&lt;Class, MockInvocationHandler&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> mock<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		MockInvocationHandler h = <span style="color: #000000; font-weight: bold;">new</span> MockInvocationHandler<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>MocksControl<span style="color: #66cc66;">&#41;</span> EasyMock.<span style="color: #006600;">createControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		mocks.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>type, h<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> replay<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mocks.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">replay</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> verify<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mocks.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">verify</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Finally, the base class for the aspect that does the actual work is also quite simple:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMockAspect <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> aroundStaticMethods<span style="color: #66cc66;">&#40;</span>ProceedingJoinPoint jp<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">Class</span> type = jp.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringType</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInvocationHandler+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InvocationHandler</span></a> h = getInvocationHandler<span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>h == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> jp.<span style="color: #006600;">proceed</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
		MethodSignature methodSignature = <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>MethodSignature<span style="color: #66cc66;">&#41;</span>jp.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> h.<span style="color: #006600;">invoke</span><span style="color: #66cc66;">&#40;</span>type, methodSignature.<span style="color: #006600;">getMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, jp.<span style="color: #006600;">getArgs</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> MockInvocationHandler getInvocationHandler<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #66cc66;">&#40;</span>StaticMock.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> StaticMock.<span style="color: #006600;">mocks</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>h3. Notes</p>
<p>Things to note and think about:<br />
* Static methods and native methods can be mocked! By using the "call" pointcut we change all code that tries to call the native methods and not the native method itself.<br />
* AspectJ is required to make this work. I have been using <a href="http://www.eclipse.org/ajdt/">Eclipse AJDT</a><br />
* It should be possible to replace the Aspect with "plain" byte code manipulation and "just" reload the class. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

