<?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; powermock</title>
	<atom:link href="http://blog.jayway.com/tag/powermock/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>PowerMock for Integration Testing</title>
		<link>http://blog.jayway.com/2011/05/19/powermock-for-integration-testing/</link>
		<comments>http://blog.jayway.com/2011/05/19/powermock-for-integration-testing/#comments</comments>
		<pubDate>Thu, 19 May 2011 19:34:03 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8404</guid>
		<description><![CDATA[A while ago I blogged about how to use the PowerMock Rule to bootstrap PowerMock without using a JUnit runner. A problem that you'll likely run into sooner or later when using this approach in an integration test is the need to ignore certain classes or packages from being loaded by the PowerMock classloader using [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I <a href="http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/">blogged</a> about how to use the <a href="http://www.powermock.org">PowerMock</a> <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">Rule</a> to bootstrap PowerMock without using a JUnit runner. A problem that you'll likely run into sooner or later when using this approach in an integration test is the need to ignore certain classes or packages from being loaded by the PowerMock classloader using the <code>@PowerMockIgnore</code> annotation. This is actually not limited to the Rule but happens when using the standard JUnit runner as well but it's much more likely to occur in an integration test. Frequent candidates for this are various XML, log, and persistence frameworks . The reason is that some frameworks tries to instantiate classes using reflection and does this from the thread context classloader (PowerMock's classloader) but then tries to assign the created object to a field not loaded by the same classloader. So by using <code>@PowerMockIgnore</code> you can can instruct PowerMock to defer the loading of a certain package to the parent classloader. What you need to ignore is case specific but usually it's e.g. the XML framework or some packages that interact with it. E.g. <code>@PowerMockIgnore({"org.xml.*", "javax.xml.*"})</code>. </p>
<h2>Example</h2>
<p>Let's say we have a (very stupid) Spring bean like this:</p>
<pre class="java">&nbsp;
@<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AComponent+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Component</span></a>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyBean <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> CompanyRepository companyRepository;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Message generateMessage<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> SAXException <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</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> allEmployees = companyRepository.<span style="color: #006600;">getAllEmployees</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">final</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> message = StringUtils.<span style="color: #006600;">join</span><span style="color: #66cc66;">&#40;</span>allEmployees, <span style="color: #ff0000;">&quot;, &quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> id = IdGenerator.<span style="color: #006600;">generateNewId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Message<span style="color: #66cc66;">&#40;</span>id, message<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and for demonstration we'd like to mock the static method call to <code>IdGenerator.generateNewId()</code>. Let's write a simple test bootstrapped by Spring using the <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">classloader</a> version of PowerMockRule:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> MyBean myBean;
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticMethod<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: #808080; font-style: italic;">// Given</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> expectedId = 2L;
        mockStatic<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
        when<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #006600;">generateNewId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span>expectedId<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</span> Message message = myBean.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expectedId, message.<span style="color: #006600;">getId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;John Doe, Paul Anderson, Jane Doe&quot;</span>, message.<span style="color: #006600;">getContent</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;</pre>
<p>If you run this test you'll get the following error:</p>
<pre class="java">&nbsp;
java.<span style="color: #006600;">lang</span>.<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ARuntimeException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">RuntimeException</span></a>: java.<span style="color: #006600;">lang</span>.<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AClassCastException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">ClassCastException</span></a>: com.<span style="color: #006600;">sun</span>.<span style="color: #006600;">org</span>.<span style="color: #006600;">apache</span>.<span style="color: #006600;">xerces</span>.<span style="color: #006600;">internal</span>.<span style="color: #006600;">jaxp</span>.<span style="color: #006600;">DocumentBuilderFactoryImpl</span> cannot be cast to javax.<span style="color: #006600;">xml</span>.<span style="color: #006600;">parsers</span>.<span style="color: #006600;">DocumentBuilderFactory</span>
	at powermock.<span style="color: #006600;">examples</span>.<span style="color: #006600;">spring</span>.<span style="color: #006600;">CompanyRepository</span>.<span style="color: #006600;">getAllEmployees</span><span style="color: #66cc66;">&#40;</span>CompanyRepository.<span style="color: #006600;">java</span>:<span style="color: #cc66cc;">42</span><span style="color: #66cc66;">&#41;</span>
	at powermock.<span style="color: #006600;">examples</span>.<span style="color: #006600;">spring</span>.<span style="color: #006600;">MyBean</span>.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span>MyBean.<span style="color: #006600;">java</span>:<span style="color: #cc66cc;">31</span><span style="color: #66cc66;">&#41;</span>
	at org.<span style="color: #006600;">powermock</span>.<span style="color: #006600;">examples</span>.<span style="color: #006600;">spring</span>.<span style="color: #006600;">mockito</span>.<span style="color: #006600;">SpringExampleTest</span>.<span style="color: #006600;">mockStaticMethod</span><span style="color: #66cc66;">&#40;</span>SpringExampleTest.<span style="color: #006600;">java</span>:<span style="color: #cc66cc;">58</span><span style="color: #66cc66;">&#41;</span>
...
&nbsp;</pre>
<p>The reason is that <code>companyRepository.getAllEmployees()</code> implementation called from <code>MyBean</code> bean above parses the employee list using Java's XML parsing (<code>javax.xml.parsers.DocumentBuilderFactory</code>). Thus we must use the PowerMockIgnore annotation to ignore the framework:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@PowerMockIgnore<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span><span style="color: #ff0000;">&quot;org.w3c.*&quot;</span>, <span style="color: #ff0000;">&quot;javax.xml.*&quot;</span><span style="color: #66cc66;">&#125;</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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    ....
    <span style="color: #808080; font-style: italic;">// Same code as in the previous example</span>
&nbsp;</pre>
<p>Re-run the test and it'll now pass. </p>
<h2>Introducing PowerMock Java Agent</h2>
<p>To make it easier to use PowerMock for integration testing version 1.4.9 introduces yet another way to bootstrap the framework, this time using a <a href="http://code.google.com/p/powermock/wiki/PowerMockAgent">java agent</a>. Instead of using classloaders to bootstrap and perform byte-code manipulation we now use Java's instrumentation API. This means that you won't run into classloading issues as those presented in the previous example. The test looks exactly the same though:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> MyBean myBean;
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticMethod<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: #808080; font-style: italic;">// Given</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> expectedId = 2L;
        mockStatic<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
        when<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #006600;">generateNewId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span>expectedId<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</span> Message message = myBean.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expectedId, message.<span style="color: #006600;">getId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;John Doe, Paul Anderson, Jane Doe&quot;</span>, message.<span style="color: #006600;">getContent</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;</pre>
<p>Even though the test looks exactly the same the internal implementation has a lot of differences. To have a look at the real code behind the to examples have a look in subversion <a href="http://powermock.googlecode.com/svn/tags/powermock-1.4.9/examples/spring-mockito-xml">here</a> for the first example  and <a href="http://powermock.googlecode.com/svn/tags/powermock-1.4.9/examples/spring-mockito-xml-agent">here</a> for the java agent example.</p>
<h2>Round-up</h2>
<p>Using the Java agent can help you out when you run into hard-to-resolve classloading issues with PowerMock. The implementation is still experimental and we are aware of some bugs and limitations. To know more and find help getting started with the agent please have a look at the <a href="http://code.google.com/p/powermock/wiki/PowerMockAgent">documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/19/powermock-for-integration-testing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PowerMock with unsupported frameworks such as JMock</title>
		<link>http://blog.jayway.com/2010/12/28/powermock-with-unsupported-frameworks-such-as-jmock/</link>
		<comments>http://blog.jayway.com/2010/12/28/powermock-with-unsupported-frameworks-such-as-jmock/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 18:47:45 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[jmock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6844</guid>
		<description><![CDATA[Currently PowerMock builds on top of EasyMock and Mockito to provide mocking of e.g. static methods and final classes using a familiar API. What most people don't know is that it's pretty easy to benefit from PowerMock even for frameworks it doesn't support. JMock is another popular mocking framework that PowerMock currently doesn't support but [...]]]></description>
			<content:encoded><![CDATA[<p>Currently <a href="http://www.powermock.org">PowerMock</a> builds on top of <a href="http://easymock.org/">EasyMock</a> and <a href="http://www.mockito.org/">Mockito</a> to provide mocking of e.g. static methods and final classes using a familiar API. What most people don't know is that it's pretty easy to benefit from PowerMock even for frameworks it doesn't support. <a href="http://www.jmock.org/">JMock</a> is another popular mocking framework that PowerMock currently doesn't support but this article will demonstrate some examples of JMock and PowerMock.</p>
<h2>Mocking final classes</h2>
<p>Unlike EasyMock and Mockito, JMock doesn't support mocking classes out of the box. For this to work you need to have the <code>jmock-legacy</code> jar file in your classpath. But even if you have you cannot mock classes that are final:</p>
<pre class="java">&nbsp;
<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> FinalClass <span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</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> helloWorld<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> <span style="color: #ff0000;">&quot;Hello world&quot;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>But here PowerMock can help. What you need to do is to use the PowerMock JUnit runner and to prepare the <code>FinalClass</code> for test:</p>
<pre class="java">&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>FinalClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>But unfortunately this is not enough. For PowerMock to work it needs something called a "ProxyFrameworkImpl" that helps the reflection utilities in PowerMock to find an unproxied class type of a proxied class. It also needs an "AnnotationEnabler" that's used for injecting mocks. This may sound complicated but since JMock is using CGLib to create class proxies you can use PowerMock's EasyMock implementation of the "ProxyFrameworkImpl" and "AnnotationEnabler". This works because EasyMock is also using CGLib. Thus you need to put the <a href="http://repo1.maven.org/maven2/org/powermock/powermock-api-easymock/1.4.7/powermock-api-easymock-1.4.7.jar">powermock-api-easymock.jar</a> in your class-path (note that you don't need the easymock.jar in the classpath).</p>
<p>Once we have the <a href="http://repo1.maven.org/maven2/org/powermock/powermock-api-easymock/1.4.7/powermock-api-easymock-1.4.7.jar">powermock-api-easymock.jar</a> in the classpath and have added the two annotations we're ready to test the FinalClass. Here's a full example:</p>
<pre class="java">&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>FinalClass.<span style="color: #000000; font-weight: bold;">class</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> JMockFinalClassTest <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Mockery context = <span style="color: #000000; font-weight: bold;">new</span> JUnit4Mockery<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
        setImposteriser<span style="color: #66cc66;">&#40;</span>ClassImposteriser.<span style="color: #006600;">INSTANCE</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#125;</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> FinalClass tested;
&nbsp;
    @Before
    <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: #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>
        tested = context.<span style="color: #006600;">mock</span><span style="color: #66cc66;">&#40;</span>FinalClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockFinalClassWithPowerMockAndJMock<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: #808080; font-style: italic;">// Given</span>
        <span style="color: #000000; font-weight: bold;">final</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> expected = <span style="color: #ff0000;">&quot;something&quot;</span>;
        context.<span style="color: #006600;">checking</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Expectations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
            one<span style="color: #66cc66;">&#40;</span>tested<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            will<span style="color: #66cc66;">&#40;</span>returnValue<span style="color: #66cc66;">&#40;</span>expected<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</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> actual = tested.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expected, actual<span style="color: #66cc66;">&#41;</span>;
        context.<span style="color: #006600;">assertIsSatisfied</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>
<h2><del>Mocking</del> Stubbing static methods</h2>
<p>Now that we know how to mock final classes, how about static methods? The bad news is that you can't mock them. But the good news on the other hand is that PowerMock provides a <a href="http://powermock.googlecode.com/svn/docs/powermock-1.4.7/apidocs/org/powermock/api/support/membermodification/MemberModifier.html">MemberModification</a> API that allows you to stub, suppress and replace methods. So to stub a static method regardless of the underlying mock framework you can do:</p>
<pre class="java">&nbsp;
stub<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>ClassWithStaticMethod.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;staticMethodName&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toReturn</span><span style="color: #66cc66;">&#40;</span>someObject<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>To demonstrate how this can be used with JMock imagine that we want to test the <code>generateMessage</code> method in this example:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JMockExample <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> FinalClass finalClass;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> JMockExample<span style="color: #66cc66;">&#40;</span>FinalClass finalClass<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;">finalClass</span> = finalClass;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</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> generateMessage<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> <span style="color: #ff0000;">&quot;Message is: &quot;</span>+ finalClass.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + ClassWithStaticMethod.<span style="color: #006600;">returnString</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>where <code>FinalClass</code> is the same as in the previous example and <code>ClassWithStaticMethod</code> looks like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ClassWithStaticMethod <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> returnString<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> <span style="color: #ff0000;">&quot;a string&quot;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>A full JMock test with PowerMock can look like this:</p>
<pre class="java">&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><span style="color: #66cc66;">&#123;</span>FinalClass.<span style="color: #000000; font-weight: bold;">class</span>, ClassWithStaticMethod.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#125;</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> JMockStaticMethodTest <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Mockery context = <span style="color: #000000; font-weight: bold;">new</span> JUnit4Mockery<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
        setImposteriser<span style="color: #66cc66;">&#40;</span>ClassImposteriser.<span style="color: #006600;">INSTANCE</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#125;</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> FinalClass finalClassMock;
    <span style="color: #000000; font-weight: bold;">private</span> JMockExample tested;
&nbsp;
    @Before
    <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: #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>
        finalClassMock = context.<span style="color: #006600;">mock</span><span style="color: #66cc66;">&#40;</span>FinalClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
        tested = <span style="color: #000000; font-weight: bold;">new</span> JMockExample<span style="color: #66cc66;">&#40;</span>finalClassMock<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> stubbingAndMockingWithPowerMockAndJMock<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: #808080; font-style: italic;">// Given</span>
        context.<span style="color: #006600;">checking</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Expectations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#123;</span>
            one<span style="color: #66cc66;">&#40;</span>finalClassMock<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">helloWorld</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            will<span style="color: #66cc66;">&#40;</span>returnValue<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Hello &quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Stub the static method</span>
        stub<span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#40;</span>ClassWithStaticMethod.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #ff0000;">&quot;returnString&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toReturn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;JMock&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</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> message = tested.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Message is: Hello JMock&quot;</span>, message<span style="color: #66cc66;">&#41;</span>;
        context.<span style="color: #006600;">assertIsSatisfied</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>You can check out the examples from our <a href="http://powermock.googlecode.com/svn/trunk/examples/jmock/">SVN repo</a>.</p>
<h2>Notes</h2>
<p>JMock also provides its own JUnit runner called "JMock" that automatically calls <code>context.assertIsSatisfied()</code> after each test. Normally you can use PowerMock with other JUnit runners using the <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">PowerMockRule</a> but unfortunatley the JMock runner extends from a deprecated runner which doesn't support rules.</p>
<h2>Conclusion</h2>
<p>As you can see it's pretty simple to use some PowerMock basics even for unsupported frameworks as JMock. Of course it's possible to create full-blown support for JMock using PowerMock to enable e.g. new instance and static method mocking but until that day it's good to know that alternatives exist. If you're interested to know more about PowerMock please visit our <a href="http://www.powermock.org">webpage</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/12/28/powermock-with-unsupported-frameworks-such-as-jmock/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using PowerMock with Spring integration testing</title>
		<link>http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/</link>
		<comments>http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 16:13:51 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6827</guid>
		<description><![CDATA[I quite often get the question if PowerMock can be used together with Spring integration testing or other frameworks that require a JUnit runner to bootstrap. The answer up until now has been somewhat ambiguous. The reason is that for the last year or so we've been working with a new way of bootstrapping PowerMock [...]]]></description>
			<content:encoded><![CDATA[<p>I quite often get the question if <a href="http://www.powermock.org">PowerMock</a> can be used together with Spring integration testing or other frameworks that require a JUnit runner to bootstrap. The answer up until now has been somewhat ambiguous. The reason is that for the last year or so we've been working with a new way of bootstrapping PowerMock that uses a <a href="http://www.infoq.com/news/2009/07/junit-4.7-rules">JUnit Rule</a> instead of a JUnit runner. Implementing this rule proved to be quite hard since it required deep-cloning of an entire object graph into another classloader (more info about this <a href="http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/">here</a>). For example we ran into very strange problems that caused the JVM to crash on some environments while it worked in others. In the new release of PowerMock 1.4.7 we refactored the classloader execution from the deep-cloning and made the deep-cloning implementations pluggable. This means that we now have an option to use <a href="http://xstream.codehaus.org/">X-Stream</a> as deepcloner which proves to be more robust than our <a href="http://code.google.com/p/objenesis/">Objenesis</a> implementation (albeit not as fast, not as precise and not as cool <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).</p>
<h2>Naive example</h2>
<p>Let's say we have a very simple Spring bean like this:</p>
<pre class="java">&nbsp;
@<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AComponent+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Component</span></a>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyBean <span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Message generateMessage<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;">final</span> <span style="color: #993333;">long</span> id = IdGenerator.<span style="color: #006600;">generateNewId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Message<span style="color: #66cc66;">&#40;</span>id, <span style="color: #ff0000;">&quot;My bean message&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and we want to test the <code>generateMessage</code> method in an integration test. In this test we assume that it's really important for us to mock the static call to <code>IdGenerator.generateNewId()</code>. But in order to run the test as a Spring integration test we need to use the <code>SpringJUnit4ClassRunner</code> which prevents us from using the <code>PowerMockRunner</code>. So by taking advantage of the <code>PowerMockRule</code> we can still benefit from PowerMock's functionality:</p>
<pre class="java">&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;classpath:/example-context.xml&quot;</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</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> SpringExampleTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
    @Rule
    <span style="color: #000000; font-weight: bold;">public</span> PowerMockRule rule = <span style="color: #000000; font-weight: bold;">new</span> PowerMockRule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">private</span> MyBean myBean;
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticMethod<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: #808080; font-style: italic;">// Given</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> expectedId = 2L;
        mockStatic<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
        when<span style="color: #66cc66;">&#40;</span>IdGenerator.<span style="color: #006600;">generateNewId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">thenReturn</span><span style="color: #66cc66;">&#40;</span>expectedId<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// When</span>
        <span style="color: #000000; font-weight: bold;">final</span> Message message = myBean.<span style="color: #006600;">generateMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Then</span>
        assertEquals<span style="color: #66cc66;">&#40;</span>expectedId, message.<span style="color: #006600;">getId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;My bean message&quot;</span>, message.<span style="color: #006600;">getContent</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;</pre>
<p>If you're used to PowerMock you can see that the only difference between this test and a standard PowerMock test is that we use the <code>PowerMockRule</code> instead of the </code>PowerMockRunner</code>. You can find the complete example in our SVN <a href="http://powermock.googlecode.com/svn/tags/powermock-1.4.7/examples/spring-mockito">repo</a>.</p>
<h2>Limitations</h2>
<p>For trivial tests like this the Objenesis deep-cloner works just as well as the X-Stream version but in more complex situations X-Stream is more robust. There may still be bugs lurking around and we're thankful for contributions. For example it's not possible to mock <a href="http://code.google.com/p/powermock/wiki/MockSystem">system classes</a> using any of the implementations yet.</p>
<h2>Conclusion</h2>
<p>We'll continue to work on the Objenesis deep-cloner but until it's working better you can use the X-Stream version to combine PowerMock with frameworks that require a JUnit runner. Please refer to <a href="http://code.google.com/p/powermock/wiki/PowerMockRule">this page</a> to get started with the rule.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/12/28/using-powermock-with-spring-integration-testing/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Classloader Deep-Cloning without Serialization</title>
		<link>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/</link>
		<comments>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 11:46:14 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[classloader]]></category>
		<category><![CDATA[deep-cloning]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[manipulate]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4000</guid>
		<description><![CDATA[Background In PowerMock we're using a custom classloader to byte-code manipulate classes that are normally not mockable to make them mockable. But when running a test case there may be some cases when the user needs to byte-code manipulate a certain class (X) in the first test method but needs to have the class unmodified [...]]]></description>
			<content:encoded><![CDATA[<h2>Background</h2>
<p>In <a href="http://www.powermock.org">PowerMock</a> we're using a custom classloader to byte-code manipulate classes that are normally not mockable to make them mockable. But when running a test case there may be some cases when the user needs to byte-code manipulate a certain class (X) in the first test method but needs to have the class unmodified in the second. For example you may want to remove the static initializer of class X in testA but in testB you want the static initializer intact. There's no standard way for a Java classloader to reload a class that has already been loaded so what to do? The solution is to execute that particular test method in a new classloader. Using this approach we can simply load X again and this time we won't modify it. In PowerMock we've also implemented a custom JUnit runner which allows us to execute certain test-methods in another classloader. Without going into too much detail the problem is that we need to execute some test methods in a new classloader as well as being able to supply and receive state between our classloaders. The end user shouldn't be aware that the unit test they're running is actually chunked up into several different JUnit test cases executed in many different classloaders.</p>
<h2>Requirements</h2>
<p>Our goal was to be able to execute any block of code in any given classloader without using any byte-code manipulation. We can't make any assumptions about the class such as it being serializable or having a default constructor. We also need the outcome of this code-block to be used by the original/invoking classloader. </p>
<h2>Solution</h2>
<p>The solution was to implement a <a href="http://code.google.com/p/powermock/source/browse/trunk/classloading/src/main/java/org/powermock/classloading/ClassloaderExecutor.java">ClassLoaderExecutor</a> which takes a <code>Runnable</code> or <code>Callable</code> and executes this code-block in any classloader. In the case of <code>Callable</code> the result from the callable invocation is cloned back to the original classloader calling the method. Let's look at an example. </p>
<p>First we define the code-block to be executed in the other classloader:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyCodeBlock <span style="color: #000000; font-weight: bold;">implements</span> Callable&lt;MyResult&gt;
	<span style="color: #808080; font-style: italic;">/*
         * All code inside this method will be executed in a different class-loader.
         */</span>
	<span style="color: #000000; font-weight: bold;">public</span> MyResult call<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>
		OperationToExecute operationToExecute = <span style="color: #000000; font-weight: bold;">new</span> OperationToExecute<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		...
		<span style="color: #000000; font-weight: bold;">return</span> operationToExecute.<span style="color: #006600;">execute</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>Then we simply execute this block using the <code>ClassLoaderExecutor</code>:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Instantiate the classloader where the code-block should be executed.</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AClassLoader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">ClassLoader</span></a> myClassloader = <span style="color: #000000; font-weight: bold;">new</span> MyCustomClassLoader<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Initialize the ClassLoaderExecutor with the classloader</span>
ClassLoaderExecutor classLoaderExecutor = <span style="color: #000000; font-weight: bold;">new</span> ClassLoaderExecutor<span style="color: #66cc66;">&#40;</span>myClassloader<span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">/*
 * Pass in the code-block to the ClassLoaderExecutor. The code inside
 * the call method will be executed in the &quot;myClassloader&quot;
 * and the result (MyResult) will be usable from the invoking
 * classloader (the one that called the execute method).
 */</span>
MyResult result = classLoaderExecutor.<span style="color: #006600;">execute</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MyCodeBlock<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
...
&nbsp;</pre>
<h2>How does it work?</h2>
<p>The first thing that happens when execute is called is that almost the entire object graph of the code-block is deep-cloned into the target classloader (myClassloader in the example above). The objects that are not cloned are those whose classes reside in the <code>rt.jar</code> which are always loaded by the bootstrap classloader. These objects are (in the simple cases) only referred to by a cloned object. Since we cannot make any assumptions about the class structure or hierarchy we cannot simply do deep-cloning using standard Java serialization. Neither can we clone the objects using simple reflection because how do we know which constructor to invoke when instantiating the object using the target classloader? Essentially the trick is to instantiate the class without executing any constructor at all. When this is done we iterate over all fields and instantiate and copy their values recursively. But how can you instantiate a class without invoking a constructor? Unfortunately there's no standard way of doing this. In a modern Sun JVM you can use <code>sun.reflect.ReflectionFactory</code> but it's not guaranteed that other JVM's have implemented this class. To make it more compatible we make use of the excellent <a href="http://code.google.com/p/objenesis/">Objenesis</a> framework whose sole purpose is to accommodate this across multiple JVM's from different vendors. When all state has been copied from the source to the target classloader using this approach the result of the callable operation (myResult in the example above) is cloned back from the target to the source classloader. This means that the result is directly usable from the source classloader after the execute method has finished.</p>
<h2>Conclusion</h2>
<p>This article has demonstrated one approach of executing a block of code in any given classloader using deep-cloning without serialization. There are many corner cases which we haven't dealt with here such as dealing with arrays, lists, enum, static final fields, object references etc that the <code>ClassLoaderExecutor</code> also supports. An alternative may be to use <a href="http://xstream.codehaus.org/">XStream</a> as deep-cloner to serialize the object graph to XML and de-serialize it back to  the target classloader but the approach suggested here should potentially be faster.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/23/classloader-deep-cloning-without-serialization/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PowerMock + TestNG = True</title>
		<link>http://blog.jayway.com/2009/12/14/powermock-testng-true/</link>
		<comments>http://blog.jayway.com/2009/12/14/powermock-testng-true/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 19:07:57 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3939</guid>
		<description><![CDATA[After having it on our todo list for at least a year we've finally managed to integrate PowerMock with TestNG 5.11 as of PowerMock version 1.3.5. This is a big milestone of the project since we've now demonstrated that PowerMock is decoupled from both a specific test framework and a specific mock framework. The TestNG [...]]]></description>
			<content:encoded><![CDATA[<p>After having it on our todo list for at least a year we've finally managed to integrate <a href="http://www.powermock.org">PowerMock</a> with <a href="http://www.testng.org">TestNG</a> 5.11 as of PowerMock version 1.3.5. This is a big milestone of the project since we've now demonstrated that PowerMock is decoupled from both a specific test framework and a specific mock framework. The TestNG integration still needs improvements and we're happy for all suggestions, comments or patches. </p>
<p>So how do you configure PowerMock to use TestNG? First of all follow the instructions on the <a href="http://code.google.com/p/powermock/wiki/GettingStarted">getting started</a> page which states everything you need to know to get started with or without Maven. The trick is then to specify the PowerMock object factory in the TestNG suite.xml. An example can be seen here: </p>
<pre class="brush:java">
<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
    <test name="dgf">
        <classes>
            <class name="com.mycompany.Test1"/>
            <class name="com.mycompany.Test2"/>
        </classes>
    </test>
</suite>
</pre>
<p>Without specifying this object factory the test will never be bootstrapped properly by PowerMock and thus will fail if any PowerMock functionality is used in the test.</p>
<h3>Example</h3>
<p>Now that we know how to bootstrap PowerMock and TestNG what does a test look like? If you're used to PowerMock there will be no surprises. As usually you have to prepare the class that is normally not testable/mockable for test using the <code>@PrepareForTest</code> annotation. Consider that we have a class like this:</p>
<pre class="brush:java">
public class ClassUnderTest {
	public void methodToTest() {
	   ..
	   final long id = IdGenerator.generateNewId();
	   ..
	}
}
</pre>
<p>When testing this class we might want to mock the static call to the IdGenerator. The full test will look like this using the Mockito extension API:</p>
<pre class="brush:java">
@PrepareForTest(IdGenerator.class)
public class MyTestClass {
    @Test
    public void demoStaticMethodMockingUsingTestNGAndMockito() throws Exception {
        mockStatic(IdGenerator.class);

        when(IdGenerator.generateNewId()).thenReturn(2L);               

        new ClassUnderTest().methodToTest();

        // Optionally verify that the static method was actually called
        verifyStatic();
        IdGenerator.generateNewId();
    }
}
</pre>
<p>Using the EasyMock API extension the test could look like this:</p>
<pre class="brush:java">
@PrepareForTest(IdGenerator.class)
public class MyTestClass {
    @Test
    public void demoStaticMethodMockingUsingTestNGAndEasyMock() throws Exception {
        mockStatic(IdGenerator.class);

        expect(IdGenerator.generateNewId()).andReturn(2L);

	replayAll();

        new ClassUnderTest().methodToTest();

        verifyAll();
    }
}
</pre>
<h3>Advanced</h3>
<p>Under the hood the PowerMock object factory also creates a proxy around the test class. This proxy adds support for creating and injecting mocks using the <code>@Mock</code> annotation and clears state created by PowerMock between each test. This means that you can create and inject mocks to your test like this:</p>
<pre class="brush:java">
@PrepareForTest(MyFinalClassExample.class)
public class MockInjectionTest {

    @Mock
    private MyFinalClassExample myExampleMock;

    @Test
    public void demoMockInjection() throws Exception {
	..
	expect(myExampleMock.myExample()).andReturn(8);
	..
    }
}
</pre>
<p>This works for both the EasyMock and Mockito API extensions. If you for some reason doesn't like that your test class is proxied you can manually extend the <code>org.powermock.modules.testng.PowerMockTestCase</code> to get the same functionality.</p>
<h3>Round up</h3>
<p>There's still much work to be done with the TestNG object factory such as getting better support for scoped injections and getting PowerMock test listeners in place. If you'd like to contribute in any way just drop us a note using the mailing list. Last but not least we would like to thank Dan Fabulich of the TestNG team for all the help making this possible.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/14/powermock-testng-true/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Mocking static methods in Java system classes</title>
		<link>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/</link>
		<comments>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/#comments</comments>
		<pubDate>Sun, 17 May 2009 10:34:11 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1714</guid>
		<description><![CDATA[As you may already know PowerMock can be used to easily mock static methods which is normally not possible with standard mock frameworks such as EasyMock, JMock or Mockito. All you have to do is to use mockStatic in one of the PowerMock extension API's as well as telling PowerMock to enable the class for [...]]]></description>
			<content:encoded><![CDATA[<p>As you may already know <a href="http://www.powermock.org">PowerMock</a> can be used to easily mock static methods which is normally not possible with standard mock frameworks such as EasyMock, JMock or Mockito. All you have to do is to use <code>mockStatic</code> in one of the PowerMock extension API's as well as telling PowerMock to enable the class for testing using the @PrepareForTest annotation. A simple example of this can be seen below (using the EasyMock extension API):</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Greeter <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> getGreeting<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> name<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #ff0000;">&quot;Greetings &quot;</span> + string;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>And the test:</p>
<pre class="java">&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> Greeter.<span style="color: #000000; font-weight: bold;">class</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> MockStaticExampleTest <span style="color: #66cc66;">&#123;</span>
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> mockStaticExample<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>
		<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> expectedGreeting = <span style="color: #ff0000;">&quot;greeting&quot;</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> nameToGreet = <span style="color: #ff0000;">&quot;name&quot;</span>;
&nbsp;
		mockStatic<span style="color: #66cc66;">&#40;</span>Greeter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		expect<span style="color: #66cc66;">&#40;</span>Greeting.<span style="color: #006600;">getGreeting</span><span style="color: #66cc66;">&#40;</span>nameToGreet<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>expectedGreeting<span style="color: #66cc66;">&#41;</span>;
		replayAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<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> actualGreeting = Greeter.<span style="color: #006600;">getGreeting</span><span style="color: #66cc66;">&#40;</span>nameToGreet<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verifyAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Expected and actual greeting did not match&quot;</span>,
                                  expectedGreeting, actualGreeting<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The "power" behind PowerMock lies in its ability to modify the byte-code of the classes specified in the PrepareForTest annotation to make them testable. But because of restrictions enforced by the Java run-time PowerMock is simply not allowed to byte-code manipulate certain classes dynamically. These classes are those that are loaded by Java's bootstrap class-loader such as for example <code>java.net.URLEncoder</code>, <code>java.lang.System</code> and other "system classes" located in the java.lang or java.net package etc. While is this generally not a problem it may be so if you need to mock static methods in these classes because PowerMock cannot prepare them for test. So how do we get around this problem?</p>
<h3>How does PowerMock work?</h3>
<p>To start of with we probably should describe how PowerMock actually works under hood. What happens when PowerMock makes a class testable is that the byte-code is changed so that each method call, constructor call, field call etc are first routed to something that we refer to as the MockGateway. Simply put the MockGateway decides if it's OK for the call to be delegated to the original method/constructor/field or if a mock object should be returned instead. The MockGateway communicates with a MockRepository which stores all mock objects that has been setup for the current test method. Since PowerMock is just a layer on top of other mock frameworks we leave it for the underlying framework to do the actual mock creation, recording and verification of the mocks. The created mocks are put into the MockRepository by the PowerMock mock extension API. Basically all standard mock frameworks use CGLib to create a mock object which means that they're based on a hierarchical model (CGLib creates a sub class of the class to test at run-time which is the actual mock object) instead of a delegation model which PowerMock uses through it's byte-code manipulation by delegating to the MockGateway. This means that e.g. if a class is final CGLib cannot create a sub-class of it at run-time and therefore we can't mock it. So this is why most mock frameworks have the limitations that PowerMock doesn't.</p>
<h3>So how do we mock static methods in a system class?</h3>
<p>Since there's no way for PowerMock to modify the byte-code of a system class how do we route all calls to the MockGateway? The answer is quite simple, don't modify the system class itself but modify the class calling the system class! Thus outgoing calls to methods in the system class can be routed to the MockGateway instead of the system class intercepting incoming calls. That sounds simple enough but there's one more catch. As we saw earlier you set up expectations in the EasyMock extension API by reusing the standard expect method, e.g. </p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span>Greeting.<span style="color: #006600;">getGreeting</span><span style="color: #66cc66;">&#40;</span>nameToGreet<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>expectedGreeting<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>and this usually works fine because <code>Greeting </code>has been prepared for test and the call to method <code>getGreeting</code> is routed to the MockGateway. But in cases of system classes a call to a static method is NOT intercepted by the system class itself as described above and thus the call is never routed to the MockGatway. The solution is to prepare the actual test class for test as well so that the outgoing method call to <code>getGreeting</code> in the expect method is routed to the MockGateway as well! So let's look at a very simple example to demonstrate how to mock a call to <code>URLEncoder.encode(..)</code>:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyEncoder
	<span style="color: #000000; font-weight: bold;">public</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> performEncode<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%3AUnsupportedEncodingException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">UnsupportedEncodingException</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AURLEncoder+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">URLEncoder</span></a>.<span style="color: #006600;">encode</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something&quot;</span>, <span style="color: #ff0000;">&quot;encoding&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and the test:</p>
<pre class="java">&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> <span style="color: #66cc66;">&#123;</span> MyEncoder.<span style="color: #000000; font-weight: bold;">class</span>, MyEncoderTest.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #66cc66;">&#125;</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> MyEncoderTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> demoOfSystemClassMocking<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>
		mockStatic<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AURLEncoder+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">URLEncoder</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		expect<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AURLEncoder+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">URLEncoder</span></a>.<span style="color: #006600;">encode</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something&quot;</span>, <span style="color: #ff0000;">&quot;encoding&quot;</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;something else&quot;</span><span style="color: #66cc66;">&#41;</span>;
		replayAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;something else&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> MyEncoder<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">performEncode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verifyAll<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>
<h3>But wait, will this work for <em>final</em> system classes?</h3>
<p>That's a really good question because as we said earlier PowerMock delegates the mock creation process to the underlying mock framework (such as EasyMock) which uses CGLib. So even when mocking static methods the underlying mock framework is still used to create the CGLib mock of the class where the static methods are located. PowerMock then make use of the underlying framework's functionality to hold state for all recorded method invocations etc so that we don't have to deal with that in PowerMock as well. So usually what PowerMock does when it encounters a final class that should be prepared for test is simply to remove the final modifier. This means that CGLib can be used to create the mock object of this class without any problems. But what about a final system class? There's no way for PowerMock to remove the final modifier of a system class so what to do? What PowerMock does in these cases is to create a completely new class at run-time with the exact same structure as the original final system class. I.e. all method names and their corresponding signature are copied to a this new replica class. To allow for partial mocking all static methods of the replica class delegates to the original method in the final system class. It's also the replica class that is being mocked by the underlying mock framework instead of the original system class. The MockGateway then figures out that all methods bound for this particular system class should be routed to the replica mock instead. Thus mocking of static methods in final system classes such as <code>java.lang.System</code> or <code>java.lang.String</code> works as well. As a side note it would actually be possible to use this technique to implement duck-typing in Java as well. Anyway, here's an example to demonstrate what we've just said:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SystemPropertyMockDemo <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</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> getSystemProperty<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%3AIOException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IOException</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</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;">getProperty</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;property&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and the test:</p>
<pre class="java">&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> <span style="color: #66cc66;">&#123;</span> SystemPropertyMockDemo.<span style="color: #000000; font-weight: bold;">class</span>, SystemPropertyMockDemoTest.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #66cc66;">&#125;</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> SystemPropertyMockDemoTest
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> demoOfFinalSystemClassMocking<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>
		mockStatic<span style="color: #66cc66;">&#40;</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: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		expect<span style="color: #66cc66;">&#40;</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;">getProperty</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;property&quot;</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;my property&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		replayAll<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;my property&quot;</span>,
                                  <span style="color: #000000; font-weight: bold;">new</span> SystemPropertyMockDemo<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getSystemProperty</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verifyAll<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>
<h3>Conclusion</h3>
<p>As we've seen PowerMock is capable of achieving things not normally possible with standard mock frameworks because of technical limitations. Using PowerMock you can virtually choose any design you like without having to worry about the testability (or mockability to be more precise) aspects. Please visit our <a href="http://www.powermock.org">website</a> for more information and downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>PowerMock Part 2</title>
		<link>http://blog.jayway.com/2009/05/01/powermock-part-2/</link>
		<comments>http://blog.jayway.com/2009/05/01/powermock-part-2/#comments</comments>
		<pubDate>Fri, 01 May 2009 09:00:25 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2899</guid>
		<description><![CDATA[In JayView 17 we presented a short introduction to PowerMock, a framework that allows you to create automated tests for almost any code in isolation from its environment. In this article we’ll dig a bit deeper into PowerMock and explore the goals and more of its feature set. Background PowerMock is intended for developers who [...]]]></description>
			<content:encoded><![CDATA[<p><strong>In JayView 17 we presented a short introduction to PowerMock, a framework that allows you to create automated tests for almost any code in isolation from its environment. In this article we’ll dig a bit deeper into PowerMock and explore the goals and more of its feature set.</strong></p>
<h2>Background </h2>
<p>PowerMock is intended for developers who want to unit test code in isolation from its environment. The environment may be for example other classes or<br />
objects, other systems such as a database or a file-system. To isolate the unit you<br />
can use a technique called mocking. Mocks let you record and verify behavior<br />
according to your needs in order to get a deterministic behavior when executing<br />
your test, for example provide a certain return value. A similar technique is stubs<br />
that simply remove functionality and you don’t care about the return value. </p>
<h2>Why?</h2>
<p>There already exists frameworks that provide both mocks and stubs, so why<br />
create another one? First of all PowerMock is not a new framework built from<br />
scratch, instead it extends existing mock frameworks such as EasyMock and<br />
Mockito. In most cases these frameworks are still sufficient. However, there are<br />
cases when more power is needed! </p>
<p>To be able to use mock objects your code needs to be designed in a way that<br />
makes it possible to replace collaborators, for example by using the Dependency<br />
Injection pattern. Most often this is a good thing, but sometimes it leads to more<br />
complexity and a more complicated production code that is more difficult to<br />
understand. Another problem is legacy code which is seldom designed with unit<br />
testing in mind. When trying to introduce Dependency Injection you are often<br />
forced to perform a gigantic refactoring touching almost every class. Depending<br />
on how brave you are this can either be a problem or an opportunity. </p>
<p>Another common situation is when there is some initialization routine in your<br />
code or some third party library that does something that prevents you from<br />
unit testing your code. This can both be a constructor or a static initializer. For<br />
example, did you know that an interface can have a static initializer? This means<br />
that just implementing an interface can execute code beyond your control!  </p>
<h2>Goals</h2>
<p>Since there are many good mock frameworks out there already we think that<br />
instead of creating something entirely new we want to reuse the API’s that<br />
people already use and extend them with more capabilities. This means that<br />
PowerMock consists of extension APIs to other popular mock frameworks.<br />
EasyMock was the first API that we supported since we have been using it a lot.<br />
In version 1.1 we also have some basic support for Mockito and we have serious<br />
plans for a JMock extension. PowerMock is fully extendable and you can create<br />
an extension on your own as well. </p>
<p>A key goal of PowerMock is to allow you to unit test your code without having to<br />
think about the testability aspects. We would of course never encourage you to<br />
write inflexible code that is hard to maintain, but we leave the design decisions<br />
up to you and not to the technical limitations of a test or mock framework. </p>
<p>Another important goal is that PowerMock should be just another jar file. As a<br />
user you should not have to care how PowerMock does its magic. You just put it<br />
in your classpath and then you’re good to go. You don’t need to install any IDE<br />
plugin, change the JVM settings or mess with your build environment.</p>
<h2>When to use it</h2>
<h3>Using a 3rd party or legacy framework</h3>
<ul>
<li> Sometimes communication with a particular framework is done through<br />
static methods (for example Java ME). PowerMock allows you to setup<br />
expectations for these static methods and simulate the behavior you need<br />
to test.
<li> Other frameworks require you to subclass classes that contain static<br />
initializers or constructors doing something that prevents you from unit-<br />
testing your code in isolation. PowerMock allows you to remove static<br />
initializers and suppress constructors. It also allows you to mock classes<br />
inside a signed jar files even though a class is package-private.
</ul>
<h3>Design </h3>
<ul>
<li> You really want to enforce the fact that some methods are private. PowerMock allows mocking and testing of both private and final methods..
<li> You want to read or write private state from your test without adding unnecessary methods to the production code that are used only for test purposes.
<li> In some cases you want to create a new instance of an object in your production code but still be able to replace this instance with a mock object from your test.
</ul>
<h2>Examples</h2>
<p>All examples in this article are written with the EasyMock extension API.<br />
The examples are written in a way that easily demonstrates the capabilities of<br />
PowerMock and are sometimes very naive. In the examples both the code being<br />
tested and the actual test are completely pointless and is not a recommended<br />
way of coding! The reason why we use such examples is of course that code that<br />
typically need PowerMock is often quite complex and it would be hard to focus<br />
on what we are trying to demonstrate. </p>
<p>When writing tests with PowerMock you basically always need to supply<br />
two annotations at the class-level of your test as you will see in the examples<br />
below. The first is the RunWith annotation which tells JUnit to run the test<br />
with a specific JUnit runner. In PowerMock’s case you always specify the<br />
PowerMockRunner, i.e. @RunWith(PowerMockRunner.class). This is what<br />
bootstraps the entire PowerMock framework and this is how you can see that<br />
a test is using PowerMock. The PowerMockRunner initializes PowerMock’s<br />
classloader which starts to load all classes relevant for your particular test. Some<br />
of these classes need to be prepared in order to allow for testability. These are<br />
the classes that you wish to mock, for example those containing final or static<br />
methods. You supply these classes to the @PrepareForTest annotation. What<br />
PowerMock does then is to modify the byte-code of these classes at run-time so<br />
that they become testable. Let’s look at a couple of examples to clear things up. </p>
<h3>Mocking final classes or methods</h3>
<p>Imagine writing a unit test for this fictive class:</p>
<pre>
public class SomeService {
    private final SomeDao someDao;
    public SomeService(SomeDao someDao) {
        this.someDao = someDao;
    }
    public String getFormattedData() {
        String data = ”Data is missing”;
        final String actualData = someDao.getData();
        if (actualData != null) {
            data = actualData;
        }
        return data;
    }
}
</pre>
<p>For those of you who are used to unit testing it doesn’t look like any problems<br />
at first since it’s easy to inject a mock implementation of the SomeDao class to<br />
an instance of the SomeService at construction since it’s using the Dependency<br />
Injection pattern. But let’s look at the actual implementation of the SomeDao<br />
class. </p>
<pre>
public final class SomeDao extends JdbcDaoSupport {
    public final String getData() {
        /* Query a database for data,
            this is not something we want to do in a unit test */
        getJdbcTemplate().queryForObject(”some sql”, String.class);
    }
}
</pre>
<p>As you may see this class communicates with a database which is typically<br />
something we want to avoid in a unit test. The problem is that both the class<br />
and the method is final so we wouldn’t be able to mock this class with standard<br />
EasyMock. But PowerMock makes this possible using the standard EasyMock<br />
syntax: </p>
<pre>
@RunWith(PowerMockRunner.class)
@PrepareForTest(SomeDao.class)
public class SomeServiceTest {
    @Test
    public void returnedValueIsActualData() throws Exception {
        final String expectedData = ”data”;
         // We use PowerMock.createMock(..) to create
         // the mock object since it’s final.
        SomeDao someDaoMock = createMock(SomeDao.class);
        expect(someDaoMock.getState()).andReturn(expectedData);
        replayAll();
        SomeService tested = new SomeService(someDaoMock);
        final String actualData = tested.getFormattedData();
        verifyAll();
        assertEquals(expectedData, actualData);
    }
}
</pre>
<p>Looking closely you may see that we’re using the replayAll() and verifyAll()<br />
methods of the PowerMock API. These methods will replay and verify all mocks<br />
created by PowerMock so that you don’t have to keep track of them yourself.<br />
Of course PowerMock provides the standard replay(..) and verify(..) methods as<br />
well if you’d rather want to use those. </p>
<h3>Mocking and testing private methods</h3>
<p>Sometimes you may want to enforce encapsulation and use private methods.<br />
There’s a debate going on on whether one should test private methods by<br />
themselves or not but we’ll leave that decision up to you. Mocking a method<br />
of the class being tested is known as partial mocking. PowerMock lets you do<br />
partial mocking and also invoke private methods during a test. Let’s say we have<br />
the following class: </p>
<pre>
public class DataService {
    public boolean replaceData(final String dataId,
                      final byte[] binaryData) {
        // ...do something... then
        return modifyData(dataId, binaryData);
    }
    public boolean deleteData(final String dataId) {
        // ...do something else... then
        return modifyData(dataId, null);
    }
    private boolean modifyData(String dataId, byte[] binaryData) {
        // Imagine this method doing something
         // complex and expensive.
    }
}
</pre>
<p>DataService has two public methods that both calls the private modifyData<br />
method and you may want to unit test these methods. You may want to test<br />
replace replaceData without invoking modifyData or maybe just test the private<br />
method itself. PowerMock lets you do both. To mock the modifyData method<br />
you create a partial mock using PowerMock.createPartialMock(..) and to setup<br />
expectations for a private method you use the PowerMock.expectPrivate(..)<br />
method. For the replaceData method the test could look like this: </p>
<pre>@RunWith(PowerMockRunner.class)
@PrepareForTest(DataService.class)
public class DataServiceTest {
    @Test
    public void testReplaceData() throws Exception {
        final String methodName = ”modifyData”;
        final byte[] expectedBinaryData = new byte[] { 42 };
        final String expectedDataId = ”id”;
        // Mock only the modifyData method
        DataService tested =
             createPartialMock(DataService.class, methodName);
        /*
         * This is the simplest way to expect
         * a method call to a private method.
         */
        expectPrivate(tested, methodName, expectedDataId,
                expectedBinaryData).andReturn(true);
        replay(tested);
        assertTrue(tested.replaceData(expectedDataId,
                 expectedBinaryData));
        verify(tested);
    }
}</pre>
<p>PowerMock also provides utility methods located in the Whitebox class that can<br />
assist you with accessing internal state, executing private methods or constructors<br />
etc. So if we’d like to test the modifyData method instead of mocking it we can<br />
do so by using the Whitebox.invokeMethod(..) functionality: </p>
<pre>boolean success = (Boolean) Whitebox.invokeMethod(tested, ”modifyData”,
”myDataId”, new byte[]{42}); </pre>
<p>As you can see you just supply the instance containing the method, the method<br />
name itself and the arguments that you want to pass to the method. </p>
<p>Note that in general you should avoid testing and mocking private methods<br />
as these tests are often fragile and tightly coupled with the implementation.<br />
During refactoring, when you most need your test cases, you may be forced to<br />
simply throw away tests that are too tightly coupled to the old implementation.<br />
Therefore, when writing tests you should always focus on testing expected<br />
behavior and not check implementation details. </p>
<h3>Mocking new object constructions</h3>
<p>Let’s say we have a class that looks like this: </p>
<pre>
public class Directory {
    public boolean createDirectoryStructure(String directoryPath) {
        File directory = new File(directoryPath);
        if (directory.exists()) {
            throw new IllegalArgumentException(”\”” +
                directoryPath + ”\” already exists.”);
        }
        return directory.mkdirs();
    }
}
</pre>
<p>When unit testing this class we want to isolate ourselves from the file-system<br />
environment since what’s interesting for us to test whether a directory already<br />
exists or not. So what we want to do is to create a mock object of the File class<br />
and replace the file instance with this mock object. This is something that is<br />
normally not possible since we’re creating a new File instance in our code. But<br />
with PowerMock you can indeed do so: </p>
<pre>
@RunWith(PowerMockRunner.class)
@PrepareForTest( Directory.class )
public class DirectoryTest {
    @Test
    public void givenThatDirectoryDoesntExistAssertThatItIsCreated() {
        final String path = ”directoryPath”;
        File fileMock = createMock(File.class);
        expectNew(File.class, path).andReturn(fileMock);
        expect(fileMock.exists()).andReturn(false);
        expect(fileMock.mkdirs()).andReturn(true);
        replayAll();
        Directory tested = new Directory();
        assertTrue(tested.createDirectoryStructure(path));
        verifyAll();
    }
} </pre>
<p>As you can see we’re using the expectNew functionality of PowerMock to<br />
intercept the call to new File and return the mock object instead. Note that we<br />
prepare the Directory class for test and not the File class. The reason for this is<br />
that it is the Directory instance that creates a new File instance and thus the File<br />
class itself doesn’t have to be prepared for test. </p>
<h3>Suppressing unwanted behavior</h3>
<p>Sometimes you want to suppress a method, constructor or static initializer<br />
of your production code when executing your test because they are of no<br />
importance to the test or they even prevent you from testing your unit. Let’s<br />
take a look at the following example: </p>
<pre>public class ExampleWithBaseClass extends ThirdPartyFrameworkBaseClass {
    private final String message;
    public ExampleWithBaseClass(String message) {
        this.message = message;
    } 

    public String getMessage() {
        return message;
    }
}
</pre>
<p>This seems like an easy class to unit test (so easy in fact that you probably<br />
shouldn’t test it, but let’s do it anyway for demonstration purposes). But wait,<br />
let’s look at what the ThirdPartyFrameworkBaseClass class looks like: </p>
<pre>public class ThirdPartyFrameworkBaseClass {
    public ThirdPartyFrameworkBaseClass() {
        System.loadLibrary(”framework.dll”);
    }
} </pre>
<p>This class tries to load a dll file which may not be present when you run<br />
a unit test for the ExampleWithBaseClass class and thus will lead to<br />
an exception. With PowerMock you can just suppress the constructor<br />
of the ThirdPartyFrameworkBaseClass so that you can unit test the<br />
ExampleWithBaseClass class in isolation from the native framework dll.<br />
Sometimes this may also save you a lot of time not having to bootstrap an entire<br />
framework. You can achieve this by using the suppressConstructor method of<br />
the PowerMock API. In this case we would do: </p>
<pre>@RunWith(PowerMockRunner.class)
@PrepareForTest(ExampleWithBaseClass.class)
public class ExampleWithBaseClassTest {
    @Test
    public void assertThatConstructorMessageDoesntChange() throws
    Exception {
        // This is how we suppress the constructor
        suppressConstructor(ThirdPartyFrameworkBaseClass.class);
        final String message = ”myMessage”;
        ExampleWithBaseClass tested = new
        ExampleWithBaseClass(message);
        assertEquals(message, tested.getMessage());
    }
}
</pre>
<p>That’s it! PowerMock can also suppress static initializers, methods and fields.</p>
<h3>Access private state</h3>
<p>For mutable objects internal state may change after a method has been invoked.<br />
When unit testing such objects it’s good to have an easy way to get a hold of this<br />
state and see if it has updated accordingly. PowerMock supplies several useful<br />
reflection utilities specially designed for unit testing. All of these reflection<br />
utilities are located in the org.powermock.reflect.Whitebox class. </p>
<p>For demonstration purposes let’s say we have a class that looks like this: </p>
<pre>public class ServiceHolder {
    private final Set<Object> services = new HashSet<Object>();
    public void addService(Object service) {
        services.add(service);
    }
    public void removeService(Object service) {
        services.remove(service);
    }
}</pre>
<p>What we’re interested in testing here is that if we add a service we want to make<br />
sure that it’s added to the services set. But since the services field is private this<br />
is normally not so easy. But with PowerMock you can do like this: </p>
<pre>@Test
public void testAddService() throws Exception {
    ServiceHolder tested = new ServiceHolder();
    final Object service = new Object();
    tested.addService(service);
    // This is how you get the private
    // services set using PowerMock
    Set<String> services = (Set<String>)
        Whitebox.getInternalState(tested, Set.class);
    assertEquals(”Size of the \”services\” Set should be 1”,
        1, services.size());
    assertSame(”Services didn’t contain the expected service”,
            service, services.iterator().next());
} </pre>
<p>As you can see we’re using the Whitebox.getInternalState(..) functionality to<br />
get the services field from the ServiceHolder instance. Note that we specified<br />
the type of the field (Set.class) instead of specifying the name of the field. This<br />
makes the code more refactor friendly as the name of the field can change.<br />
You could have achieved the same result by using the not-so-refactor-friendly<br />
alternative Whitebox.getInternalState(tested, “services”). Sometimes you need<br />
to revert to this second approach anyway, for example if you have two fields of<br />
the same type in the class.</p>
<p>Once again, accessing private state will couple the test to the implementation<br />
and should in general be avoided. However, we have seen several cases where<br />
this has been necessary in order to test the code without compromising<br />
encapsulation in the production code. </p>
<h2>Summary</h2>
<p>As you’ve seen PowerMock is capable of mocking and testing many things that<br />
are normally difficult or even impossible. PowerMock gives you more design<br />
options and does not force you to do trade-offs in favour for testability. However,<br />
always design your tests carefully and avoid tight coupling between the test<br />
cases and implementation details. PowerMock have many more features than we<br />
have shown here and we also have a lot in store for the future. Please have a look<br />
at <a href="http://www.powermock.org">http://www.powermock.org</a> for more information, downloads and tutorials. </p>
<p><em>Johan Haleby<br />
Jan Kronquist</em>  </p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/01/powermock-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Questioning &#8220;testable design&#8221;</title>
		<link>http://blog.jayway.com/2009/04/01/questioning-testable-design/</link>
		<comments>http://blog.jayway.com/2009/04/01/questioning-testable-design/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 09:11:14 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[toos]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1480</guid>
		<description><![CDATA[After a discussion about PowerMock with @olabini on Twitter I felt I had to write a post on testability. The truth "Autonomous, re-runnable, code-based tests are objectivity good" has created a perceived truth, namely "Testable design is good design". This assumption is incorrect. The phrase "testable design" is dependent of two things; the design of [...]]]></description>
			<content:encoded><![CDATA[<p>After a <a href="http://search.twitter.com/search?max_id=1430211295&page=1&q=olabini+mattiasask">discussion about PowerMock</a> with <a href="http://twitter.com/olabini">@olabini</a> on Twitter I felt I had to write a post on testability.</p>
<p>The truth "<em>Autonomous, re-runnable, code-based tests are objectivity good</em>" has created a perceived truth, namely "<em>Testable design is good design</em>". This assumption is incorrect.</p>
<p>The phrase "testable design" is dependent of two things; the design of the code under test AND the tools used for testing the code. This is a problem when the major tools today in the Java world tells you to not test private methods, final classes<br />
and so on.</p>
<p>Yes, there is a big overlap between testable design and good design, but should the test tools you use govern your design? Conscious and good design choices should govern the structure of your code, and testability should come with that.</p>
<p><a href="http://code.google.com/p/powermock/">PowerMock</a> changes the phrase "Testable design is always good" to what it should be, and that is "Good design is always testable".</p>
<p>And when it comes to the hurt of legacy code, would you rather re-factor the code in order to write tests, or write tests to be able to re-factor the code safely?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/04/01/questioning-testable-design/feed/</wfw:commentRss>
		<slash:comments>8</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>What&#8217;s new in PowerMock 1.1</title>
		<link>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/</link>
		<comments>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 09:21:13 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[commons-logging]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[jmock]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[powermock]]></category>
		<category><![CDATA[slf4j]]></category>
		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=586</guid>
		<description><![CDATA[We're proud to announce that PowerMock 1.1 was released a couple of days ago and it has many new interesting features. Framework independence First of all the internal structure of the project has undergone major changes. PowerMock core is no longer coupled to EasyMock which means that PowerMock can now be used as a foundation [...]]]></description>
			<content:encoded><![CDATA[<p>We're proud to announce that <a href="http://www.powermock.org">PowerMock</a> 1.1 was released a couple of days ago and it has many new interesting features. </p>
<h3>Framework independence</h3>
<p>First of all the internal structure of the project has undergone major changes. PowerMock core is no longer coupled to EasyMock which means that PowerMock can now be used as a foundation for testability for other mock frameworks. Our intention is that in the future you pick a combination of a mock extension API of choice (such as EasyMock, Mockito or JMock) and a test framework of choice (such as JUnit or TestNG) to enable increased testability for your code. With the new release PowerMock has some basic support for <a href="http://www.mockito.org">Mockito</a> using the Mockito extension api. This means that you can mock final and static methods, use annotations, enable partial mocking, mocking of signed classes even if they're package private and spying of final classes and methods. Expect more features in the upcoming releases! It's possible to create your own extension API's as well so you can benefit from the PowerMock features in virtually any mock framework.</p>
<h3>Test listeners</h3>
<p>Another noteworthy feature of the new release is the test listener support. This means that you can create listeners and get notifications of various events, such as before a test method is about to execute or the outcome of an executed test method etc. The purpose of these test listeners is to provide a framework-independent way to get and react to these notifications by implementing the <code>org.powermock.core.spi.PowerMockTestListener</code> and pass it to the <code>PowerMockListener</code> annotation. PowerMock has some built-in test listeners for you to use, for example it has an <code>AnnotationEnabler</code> that let's you use annotations to create your mock objects. For example consider the following piece of code:</p>
<pre>
@RunWith(PowerMockRunner.class)
@PowerMockListener(AnnotationEnabler.class)
 public class PersonServiceTest {

 	@Mock
  	private PersonDao personDaoMock;

  	private PersonService classUnderTest;

  	@Before
  	public void setUp() {
  		classUnderTest = new PersonService(personDaoMock);
  	}
   ...
  }
</pre>
<p>Using the <code>@Mock</code> annotation eliminates the need to setup and tear-down mocks manually which minimizes repetitive test code and makes the test more readable. The <code>AnnotationEnabler</code> works for both the EasyMock and Mockito API's. You can also supply the names of the methods that you wish to mock if you want to create a partial mock, for example:</p>
<pre>
@RunWith(PowerMockRunner.class)
@PowerMockListener(AnnotationEnabler.class)
 public class PersonServiceTest {

 	@Mock("getPerson")
  	private PersonDao personDaoMock;

  	private PersonService classUnderTest;

  	@Before
  	public void setUp() {
  		classUnderTest = new PersonService(personDaoMock);
  	}
   ...
  }
</pre>
<p>This piece of code will instruct PowerMock to create a partial mock of the PersonDao where only the "getPerson" method is mocked. Since EasyMock has support for nice and strict mocks you can use the <code>@MockNice</code> and <code>@MockStrict</code> annotations to get the benefits of this.</p>
<h3>Mock policies</h3>
<p>One really cool feature of the 1.1 release is something that we refer to as mock policies. A Mock Policy can be used to make it easier to unit test some code with PowerMock in isolation from a certain framework. A mock policy implementation can for example suppress some methods, suppress static initializers or intercept method calls and change their return value (for example to return a mock object) for a certain framework or set of classes or interfaces. A mock policy can for example be implemented to avoid writing repetitive setup code for your tests. Say that you're using a framework X that in order for you to test it requires that certain methods should always return a mock implementation. Perhaps some static initializers must be suppressed as well. Instead of copying this code between tests it would be a good idea to write a reusable mock policy. </p>
<p>PowerMock 1.1 provides three mock policies out of the box for mocking slf4j, java commons-logging and log4j. Let's pick slf4j as an example and let's say you have a class that looks like this:</p>
<pre>
public class Slf4jUser {
        private static final Logger log = LoggerFactory.getLogger(Slf4jUser.class);

        public final String getMessage() {
                log.debug("getMessage!");
                return "log4j user";
        }
}
</pre>
<p>To stub all calls to the logger you can use the Slf4j mock policy that takes care of doing all necessary setup for you. You use it like this:</p>
<pre>
@RunWith(PowerMockRunner.class)
@MockPolicy(Slf4jMockPolicy.class)
public class Slf4jUserTest {
     ...
}
</pre>
<p>Note that we don't have do any setup at all to mock slf4j, the Slf4jMockPolicy takes care of this.</p>
<p>Mock policies can also be chained or nested like this:</p>
<pre>
@RunWith(PowerMockRunner.class)
@MockPolicy({MockPolicyX.class, MockPolicyY.class})
public class MyTest {
    ...
}
</pre>
<p>You can of course create your own mock policies by implementing the <code>org.powermock.core.spi.PowerMockPolicy</code> interface. For more information on mock policies please have a look at the <a href="http://code.google.com/p/powermock/wiki/MockPolicies">documentation</a>. </p>
<h3>Other</h3>
<p>There are of course many other smaller features and improvements such as the ability to suppress individual fields and better support for resetting mocks in the EasyMock API. You can read about all the new features and bug fixes in the <a href="http://powermock.googlecode.com/svn/trunk/changelog.txt">changelog</a>. Please visit our <a href="http://www.powermock.org">web-page</a> for more information and downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/feed/</wfw:commentRss>
		<slash:comments>2</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>
	</channel>
</rss>

