<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>junit &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/junit/</link>
	<description>Feed of posts on WordPress.com tagged "junit"</description>
	<pubDate>Tue, 14 Oct 2008 01:16:31 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[]]></title>
<link>http://cadsmith.wordpress.com/?p=205</link>
<pubDate>Sun, 12 Oct 2008 02:12:20 +0000</pubDate>
<dc:creator>cadsmith</dc:creator>
<guid>http://cadsmith.th.wordpress.com/2008/10/11/205/</guid>
<description><![CDATA[Read JUnit Recipes: Practical Methods for Programmer Testing, by J. B. Rainsberger and Scott Stirlin]]></description>
<content:encoded><![CDATA[<p>Read <span style="color:black;"><a title="JUnit Recipes" href="http://safari.oreilly.com/9781932394238">JUnit Recipes: Practical Methods for Programmer Testing</a>, by J. B. Rainsberger and Scott Stirling, 2004, 752 pp. <a title="JUnit Twine" href="http://www.twine.com/twine/11jck3xzw-rt/junit">Related link</a><a title="JUnit Twine" href="http://www.twine.com/twine/11jck3xzw-rt/junit">s</a>. </span></p>
<p><img class="alignnone" src="http://safari.oreilly.com/images/9781932394238/9781932394238_xs.jpg" alt="" width="76" height="95" /></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JUnit: Dealing with errors in your @After method]]></title>
<link>http://ourcraft.wordpress.com/?p=880</link>
<pubDate>Fri, 10 Oct 2008 16:08:28 +0000</pubDate>
<dc:creator>danielmeyer</dc:creator>
<guid>http://ourcraft.th.wordpress.com/2008/10/10/junit-dealing-with-errors-in-your-after-method/</guid>
<description><![CDATA[Normally, when you run a junit test and it has an error, you look at the error and it helps you figu]]></description>
<content:encoded><![CDATA[<p>Normally, when you run a junit test and it has an error, you look at the error and it helps you figure out what's wrong.  But I encountered a situation today that was a layer deeper:</p>
<p>Here's what we saw:</p>
<p><a href="http://ourcraft.files.wordpress.com/2008/10/junit-error-during-teardown-method.png"><img class="alignnone size-medium wp-image-881" title="junit-error-during-teardown-method" src="http://ourcraft.wordpress.com/files/2008/10/junit-error-during-teardown-method.png?w=300" alt="" width="300" height="96" /></a></p>
<p>A NullPointerException in the tearDown method (technically, in the @After method since we're using JUnit 4).  The error didn't give much clue as to what the cause was.</p>
<p>What happens in cases like this is that when the @After method causes an exception, that exception masks any previous exception that the @Before method or @Test method may have experienced.</p>
<p>To diagnose the problem, we comment out the contents of the @After method for the moment and then run the test again (maybe just running one test method (you can do this by opening the class in Eclipse's  Outline view, then right-clicking on one of the methods and Run As... JUnit Test) to avoid accumulating a bunch of gunk that the @After method would have cleaned up if it weren't commented out).  Now that we had removed the masking exception, the stack trace showed clearly what the problem was (in our case, there were some properties that needed to be set in a properties file).</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Pruebas Unitarias]]></title>
<link>http://softmetal.wordpress.com/?p=338</link>
<pubDate>Mon, 06 Oct 2008 01:52:24 +0000</pubDate>
<dc:creator>softmetal</dc:creator>
<guid>http://softmetal.th.wordpress.com/2008/10/06/pruebas-unitarias/</guid>
<description><![CDATA[Me pregunto, por que si la parte mas importante de un Sistema es que funcione correctamente, es a la]]></description>
<content:encoded><![CDATA[<p>Me pregunto, por que si la parte mas importante de un Sistema es que funcione correctamente, es a la etapa a la que se le da menos importancia, o solo se limita a probarla de tal forma que el mismo desarrollador o algun ayudante suyo toman el papel de usuario y utilizan la herramienta en busca de algun error; no es una mala tecnica, pero no es suficiente. ya que nunca se saben los limites de los usuarios, y no sabemos que combinacion de teclas vayan a precionar, que pueda tumbar nuestro sistema.</p>
<p>Por este motivo se crearon las famosas aplicaciones de Pruebas unitarias. Que son muy eficientes y nos permiten comprobar el estado de cada uno de los modulos de nuestro sistema, algunas de estas aplicaciones son gratuitas y otras no.</p>
<p>Algunas versiones libres son:</p>
<p><a href="http://www.nunit.org/index.php" target="_blank">NUnit (Para .Net)</a></p>
<p><a href="http://www.junit.org/" target="_blank">JUnit (Para Java)</a></p>
<p><a href="http://www.jsunit.net/" target="_blank">JSUnit (Para JavaScript)</a></p>
<p><a href="http://www.asunit.org/" target="_blank">ASUnit (Para ActionScript);</a></p>
<p>Dentro de cada una de estas paginas vienen ejemplos, Frameworks, documentacion, entre otras cosas, que nos ayudaran a facilitarnos el hacer las pruebas.</p>
<p>Cabe mencionar que Visual Studio en sus versiones TEAM, trae incluido una funcionalidad que nos permite realizar pruebas unitarias de una forma bastante simple y eficas.</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=D95598D7-AA6E-4F24-82E3-81570C5384CB&#38;displaylang=en" target="_blank">Pruebe Visual Studio 2008 Team Suite (Por 90 dias)</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[A handy feature in Firebug]]></title>
<link>http://virtualchris.wordpress.com/?p=9</link>
<pubDate>Fri, 26 Sep 2008 13:31:54 +0000</pubDate>
<dc:creator>Chris</dc:creator>
<guid>http://virtualchris.th.wordpress.com/2008/09/26/a-handy-feature-in-firebug/</guid>
<description><![CDATA[By far my favourite Firefox plugin is Firebug. It&#8217;s a web development/debugging tool that allo]]></description>
<content:encoded><![CDATA[<p>By far my favourite Firefox plugin is Firebug. It's a web development/debugging tool that allows you to view and edit a page's HTML, CSS, JS and DOM on-the-fly. When trying to debug a particularly obscure bit of layout CSS, for example, it's incredibly useful to be able to change bits of the code and see the corresponding changes to the page in real-time.</p>
<p>Firebug was written by Joe Hewitt, who worked on Netscape back in the day and wrote large parts of the early versions of Firefox. Pretty much a demi-god when it comes to browser technology. I think he works for Facebook now.</p>
<p>Anyway, I was using Firebug today and I discovered a very useful feature: Copy XPath. Anybody who has written XPath strings by hand will know that it's a very tedious and error-prone business, so this feature is a god-send.</p>
<p><a href="http://virtualchris.wordpress.com/files/2008/09/screenshot.png"><img class="alignnone size-medium wp-image-10" title="Firebug 'Copy XPath' screenshot" src="http://virtualchris.wordpress.com/files/2008/09/screenshot.png?w=300" alt="" width="300" height="187" /></a></p>
<p>Just right-click on any HTML element and choose 'Copy XPath' from the menu to copy that element's XPath to the clipboard. Just bear in mind that the generated XPath string is lowercase. XPath is (generally) case-sensitive, so you may need to convert it to uppercase to make it work.</p>
<p>This feature comes in particularly handy for some work I'm doing at the moment, namely automatic testing of a web application using <a title="Watij" href="http://watij.com" target="_blank">watij</a> (Web Application Testing In Java, pronounced 'wattage'). This is a tool that allows you to automate IE from Java, telling it to open pages, click buttons, etc. It integrates nicely with <a title="JUnit" href="http://www.junit.org" target="_blank">JUnit</a>, allowing you to unit-test your web application with ease. In an ideal world, your web-app's HTML would be liberally sprinkled with <code>name</code>s and <code>id</code>s, allowing you to easily tell watij what you want IE to do and what results you expect, but if you don't have that luxury, then really XPath is your only choice.</p>
<div class="firebugLayoutBox firebugLayoutBoxOffset" style="left:8px;top:8px;">
<div class="firebugLayoutBox firebugLayoutBoxMargin" style="padding:0 0 13px;"></div>
</div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[J2EE System Designer - 6+ Years - Valtech - Bangalore]]></title>
<link>http://jobs4umate.wordpress.com/?p=1886</link>
<pubDate>Fri, 26 Sep 2008 07:26:56 +0000</pubDate>
<dc:creator>Talentty</dc:creator>
<guid>http://jobs4umate.th.wordpress.com/2008/09/26/j2ee-system-designer-6-years-valtech-bangalore/</guid>
<description><![CDATA[Valtech, Bangalore 
Valtech is a highly regarded global business consulting and technology services]]></description>
<content:encoded><![CDATA[<p><span class="para-text-big"><span style="font-style:italic;"><span class="para-text-big"><span style="font-style:italic;"><strong><a href="http://www.valtech.co.in">Valtech</a>, Bangalore </strong></span></span></span></span></p>
<p><span class="para-text-big"><span style="font-style:italic;"><strong>Valtech </strong>is a highly regarded global business consulting and technology services company. </span></p>
<p>To help clients hit their constantly moving business targets, Valtech makes IT “business-friendly”. With thought leadership in Agile Methodology, Software Quality, IT Knowledge Transfer and Open Source solutions, Valtech provides a refreshing approach, capable of delivering sure-fire results and IT self sufficiency in any fast-paced business environment.</p>
<p>Valtech supplies management, technology and ebusiness consulting, global sourcing and learning services to forward-thinking companies. With over 1,100 employees, the company operates 17 offices located in the US, Europe and Asia. Founded in 1993, it is listed on the Paris stock exchange.</span></p>
<p><strong>Job Description: J2EE System Designer</strong></p>
<p><strong>Years of Experience : 6+ Years</strong></p>
<p><strong>Location : Bangalore</strong> </p>
<p><span class="para-text-title"><span style="color:#327d01;">Offer #IND-02-06J2EESD</span></span></p>
<p><span class="para-text-title"><span style="color:#327d01;">Skills :</span></span> Educational Qualification: BE/MCA/Equivalent J2EE/Hands on Java Experience of "big" system architecture OOAD/UML Eclipse/plug-in devlopment JMS, Web Services Design Patterns JUnit</p>
<p><span class="para-text-title"><span style="color:#327d01;">Professional experience :</span></span> Websphere Commerce SWT MQ series XML RDBMS (DB2) Rich Client (RCP) Development Agile methodology</p>
<p><span class="para-text-big"><strong>Responsibilities<br />
</strong><br />
• Ability to understand the architecture, contribute to architecture (assist architect) in coming out with a solution<br />
• Significant experience in designing systems using Object Oriented Methodologies<br />
• Help developers in resolving technical problems and to promote knowledge sharing<br />
• Perform Technical Reviews (Design/Architecture/TestDesign,Code)<br />
• Hands-on in Java coding<br />
• Strong in OOAD<br />
• Strong in Junit<br />
• Supporting the developers – making sure that the developers are able to realise the architecture, by a combination of mentoring and direct involvement<br />
• Ability to identify design patterns and implement it<br />
</span></p>
<p><span class="para-text-big">This job is posted in <a href="http://www.valtech.co.in/">http://www.valtech.co.in/</a> for more details visit <a href="http://www.valtech.co.in/in/index/careers/job/IND-02-06J2EESD.html">http://www.valtech.co.in/in/index/careers/job/IND-02-06J2EESD.html</a></span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Itep contrata profissionais graduados em Ciência da Computação]]></title>
<link>http://getvagas.wordpress.com/?p=63</link>
<pubDate>Fri, 19 Sep 2008 02:35:08 +0000</pubDate>
<dc:creator>getvagas</dc:creator>
<guid>http://getvagas.th.wordpress.com/2008/09/19/itep-contrata-profissionais-graduados-em-ciencia-da-computacao/</guid>
<description><![CDATA[Itep contrata profissionais graduados em Ciência da Computação
O Instituto de Tecnologia de Perna]]></description>
<content:encoded><![CDATA[<p><span style="color:#353535;"><span style="font-family:Arial;"><em>Itep contrata profissionais graduados em Ciência da Computação</p>
<p></em>O Instituto de Tecnologia de Pernambuco (Itep-OS) está selecionando três profissionais graduados em Ciência da Computação, Engenharia da Computação, Sistemas de Informação ou similares para atuarem na Assessoria de Interiorização. O edital com todas as informações está disponível no site </span></span><a href="http://www.itep.br/" target="_blank"><span style="color:#0068cf;font-family:Arial;">www.itep.br</span></a><span style="color:#353535;font-family:Arial;">, no link Editais e Processos Seletivos.</p>
<p>O candidato deverá encaminhar currículo para o e-mail </span><a href="mailto:selecaorh@itep.br"><span style="color:#0068cf;font-family:Arial;">selecaorh@itep.br</span></a><span style="color:#353535;font-family:Arial;">, até o dia 17 deste mês, sob o título Edital /Assessoria de Interiorização 2 – Desenvolvedor. A seleção se dará através de análise de currículo e entrevista. Após a análise dos currículos, os candidatos aprovados nesta fase serão convocados para entrevista, que acontecerá com agendamento realizado através de contato por telefone. O resultado será divulgado a partir de 23 de setembro de 2008, no site do Itep. 3. A remuneração é a combinar.</p>
<p>As vagas são para profissionais com: 1) experiência de dois anos com desenvolvimento de interface gráfica,conhecimento em técnicas de usabilidade e acessibilidade, e domínio de tecnologias de desenvolvimento Web, experiência em Java,JEE,UML,arquitetura MVC, Ajax , CSS,ferramentas gráficas para design;e inglês técnico, desejável conhecimento em PostgreSQL ,Scrum e JUnit; 2) experiência de dois anos com Java,JEE, Hibernate ,UML, Padrões de Projetos,arquiteturas de software, JSF e Spring; inglês técnico, conhecimento em PostgreSQL; desejável conhecimento em Scrum e JUnit; 3) experiência de dois anos com Java, JEE, arquitetura MVC, SQL, administração de SGBD, PostgreSQL, MySQL e Hibernate, inglês técnico;desejável conhecimento em Scrum e JUnit.</p>
<p>Mais informações<br />
</span><a href="http://www.itep.br/" target="_blank"><span style="color:#0068cf;font-family:Arial;">www.itep.br</span></a><span style="color:#353535;font-family:Arial;"> </span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[12 mẹo viết Unit Test cho Lập Trình Viên]]></title>
<link>http://doquocduy.wordpress.com/?p=62</link>
<pubDate>Thu, 18 Sep 2008 18:11:12 +0000</pubDate>
<dc:creator>Duy Do</dc:creator>
<guid>http://doquocduy.th.wordpress.com/2008/09/19/12-m%e1%ba%b9o-vi%e1%ba%bft-unit-test-cho-l%e1%ba%adp-trinh-vien/</guid>
<description><![CDATA[12 mẹo viết Unit Test cho Lập Trình Viên
Nội dung
1.    Viết Unit Test để giảm c]]></description>
<content:encoded><![CDATA[<p>12 mẹo viết Unit Test cho Lập Trình Viên</p>
<p><strong>Nội dung</strong><br />
1.    Viết Unit Test để giảm các rủi ro<br />
2.    Viết một Test Case cho mỗi component quan trọng<br />
3.    Viết Abstract Test Case và Test Utilities<br />
4.    Viết các test hiệu quả (smart tests)<br />
5.    Thiết lập môi trường phù hợp cho mỗi test<br />
6.    Sử dụng Mock Object để viết test hiệu quả hơn<br />
7.    Refactor các test khi refactor code<br />
8.    Viết test trước khi sửa lỗi<br />
9.    Sử dụng Unit Test để bảo đảm hiệu suất (performance)<br />
10.    Viết test cho concurrent code<br />
11.    Thực thi các test một cách thường xuyên<br />
12.    Lời kết<br />
-------------------------------------------------------------------------------------------------------------------------------<br />
<strong>Lời nói đầu</strong><br />
Unit Testing là một trong những phần trọng yếu của phương pháp phát triển phần mềm linh hoạt (Agile Software Development), được giới thiệu lần đầu tiên bởi Kent Beck. Unit Testing giúp lập trình viên giảm thiểu tối đa các lỗi (bug), giảm thời gian tìm kiếm lỗi (debug), tạo ra được những phần mềm có tính ổn định cao.<br />
Hầu hết mọi người đều xem nhẹ Unit Test, nếu có viết thì cũng viết cho qua loa, lấy lệ vì mọi người bảo rằng viết Unit Test mất thời gian. Đây là một suy nghĩ không đúng. Theo kinh nghiệm của mình thì đây chính là một phần gây ra việc mất thời gian debug về sau mỗi khi xảy ra lỗi, thời gian này tiêu tốn gấp nhiều lần đối với việc viết unit test.</p>
<p><!--more--></p>
<p>Trong bài viết này mình đưa ra 12 mẹo mà các lập trình viên có thể áp dụng, không quan tâm đến môi trường hay ngôn ngữ lập trình nào. Mỗi ngày mình sẽ viết 2 mẹo. Nếu các bạn có ý định phổ biến bài viết này ở nơi khác xin hãy giữ nguyên tác giả và hãy để <a href="http://doquocduy.wordpress.com/2008/09/19/12-m%e1%ba%b9o-vi%e1%ba%bft-unit-test-cho-l%e1%ba%adp-trinh-vien/">liên kết đến bài viết này trên blog</a> của mình.</p>
<p>Hôm nay mình viết 2 mẹo đầu tiên</p>
<ol>
<li><strong>Viết Unit Test để giảm các rủi ro </strong>Một lập trình viên nào đó có thể hỏi: Tại sao tôi nên viết các test case? Chứ không phải việc testing nhàm chán này có nhóm QA lo rồi sao? Với tinh thần này chúng ta sẽ không có chỗ đứng trong môi trường công nghệ phần mềm hiện đại ngày nay. Mục tiêu chính của một nhóm phát triển phần mềm là phải làm sao tạo ra được những sản phẩm phần mềm có chất lượng tốt nhất. Người dùng cuối (end-user) rất khó chấp nhận các phần mềm bị lỗi, thiếu ổn định. Hiện nay hầu hết các thư viện (lib), web service và IDE (Integrated Development Environment) đều hỗ trợ refactor và unit testing, vì thế sẽ không có lời xin lỗi nào cho những phần mềm, đoạn mã chương trình bị lỗi.<br />
Ý tưởng đằng sau Unit Testing là tạo ra tập hợp các test cho mỗi thành phần của phần mềm (software component). Unit Test tạo thuận tiện cho việc phần mềm được test liên tục; chi phí thực hiện các test này khá rẻ so với test thủ công (manual test)<br />
Mỗi test case được xem như là giấy bảo hiểm cho hệ thống phần mềm của bạn. Có một lỗi (bug) trong mã chương trình, điều đó có nghĩa là có một rủi ro tiềm ẩn trong hệ thống. Việc viết các unit test sẽ giúp cho lập trình viên giảm số lượng lỗi và các rủi ro với các đoạn mã chương trình.</li>
<li><strong>Viết một Test Case cho mỗi component quan trọng</strong>Khi bắt đầu unit testing, hãy luôn đặt ra cho mình câu hỏi: <em>Những test nào mình nên viết?</em><br />
Ban đầu nên đẩy mạnh việc viết các cụm test chức năng, nghĩa là kiểm tra thăm dò các chức năng của hệ thống. Điều này không đúng. Chỉ tạo ra một test case (một tập hợp các test) cho mỗi thành phần quan trọng (major component) của hệ thống phần mềm.<br />
Tại một thời điểm chỉ tập trung viết test cho một component . Trong phạm vi một component, hãy nhìn vào interface của component đó mà viết test. Các bạn nên viết ít nhất một test cho một phương thức public thuộc interface đề cập ở trên.</li>
</ol>
<p>Hôm nay mình tạm dừng tại đây. Hẹn các bạn ở các mẹo tiếp theo.</p>
<p>Duy Đỗ</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Running with the...]]></title>
<link>http://ourcraft.wordpress.com/?p=748</link>
<pubDate>Thu, 18 Sep 2008 15:00:40 +0000</pubDate>
<dc:creator>danielmeyer</dc:creator>
<guid>http://ourcraft.th.wordpress.com/2008/09/18/running-with-the/</guid>
<description><![CDATA[(For some reason, &#8220;Running with the bulls&#8221; sounds a lot more poetic than &#8220;Running ]]></description>
<content:encoded><![CDATA[<p>(For some reason, "Running with the bulls" sounds a lot more poetic than "Running with the right JUnit 4 test runner.")</p>
<p>I was getting a NullPointerException when I started writing the unit test for my little TransactionManager wrapper class.  I am using Unitils to manage all the dependency injection, so my test class looks something like this:</p>
<p>[sourcecode language='java']</p>
<p>public class TransactionManagerTest {<br />
    @Mock<br />
    @InjectIntoByType<br />
    private PlatformTransactionManager platformTransactionManager;</p>
<p>    @TestedObject<br />
    private TransactionManager transactionManager;</p>
<p>    @Test<br />
    public void testCommitException() {<br />
        transactionManager.commit();<br />
    }<br />
[/sourcecode]</p>
<p>I first got the NullPointerException while trying to test TransactionManager's getTransaction() method, but it has some more complex logic, so I decided to back off from that and test the commit() method first.</p>
<p>I had expected that when I called transactionManager.commit(), I would get the unchecked exception that commit() throws when you haven't called getTransaction() first.  But instead, this NullPointerException.</p>
<p><em><strong>Before looking at the answer, can you guess why that would be?</strong></em></p>
<p>Oh, wait, I already gave it away at the top of this post. Rats!</p>
<p>(Maybe there's a reason I'm a programmer instead of a game show host. ;)</p>
<p>Yup, that's right, folks!  All it was, was, I needed to...</p>
<p>[sourcecode language='java']</p>
<p>@RunWith(UnitilsJUnit4TestClassRunner.class)<br />
[/sourcecode]</p>
<p>See ya next time!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Phasing over from java to scala pt. 4 - Writing specs with specs]]></title>
<link>http://johlrogge.wordpress.com/?p=80</link>
<pubDate>Sun, 14 Sep 2008 22:05:34 +0000</pubDate>
<dc:creator>johlrogge</dc:creator>
<guid>http://johlrogge.th.wordpress.com/2008/09/14/phasing-over-from-java-to-scala-pt-4-writing-specs-with-specs/</guid>
<description><![CDATA[In the last part I figured out how to make Buildr run specs that are also runnable from Eclipse via ]]></description>
<content:encoded><![CDATA[<p>In the last part I figured out how to make Buildr run specs that are also runnable from Eclipse via JUnit. I started writing my first spec and we are now in the position to make it fail. What we are trying to acomplish is to make directories behave as nodes in a graph, at the moment, only the files show up as nodes.</p>
<p>The spec I wrote currently looks like this:</p>
<pre>class PublishSiteGraphSpecTest extends JUnit4(PublishSiteGraphSpec)
object PublishSiteGraphSpec extends Specification {
  "directories are nodes" in {
  }
}</pre>
<p>Let us fill in the details about what we actually mean when we say that directories should be nodes:</p>
<p><!--more--></p>
<pre>class PublishSiteGraphSpecTest extends JUnit4(PublishSiteGraphSpec)
object PublishSiteGraphSpec extends Specification {
  "directories are nodes" in {
    val source = new MemoryResourceRepository()
    val target = new MemoryResourceRepository()
    val problems = new ProblemsStub()
    val graph = new PublishSiteGraph(source, new SiteJobQueue(),
                                     new ContentNodeFactory(source, target, problems))
    source.importResource("directory/resource.ext",
                          new StringResource("directory/resource.ext", "the contents"))
    graph.findNode("directory") must haveClass(classOf[DirectoryNode])
  }
}</pre>
<p>And it fails with an exception saying:</p>
<pre><span style="color:#ff0000;">The file "directory" does not exist</span></pre>
<p>The problem is that MemoryResourceRepository does not add resources for the directories on the path. So we ignore this test for now and move our focus to the <em>MemoryResourceRepository</em>:</p>
<pre>class PublishSiteGraphSpecTest extends JUnit4(PublishSiteGraphSpec)
object PublishSiteGraphSpec extends Specification {
  "directories are nodes" in {
<strong>    skip("Won't work until MemoryResourceRepository adds resources for directories.")</strong>
    val source = new MemoryResourceRepository()
    ...
  }
}</pre>
<p>And now JUnit ignores the test and builder outputs this:</p>
<pre>Running tests in publisher:scala-core
Running java com.agical.publisher.content.site.PublishSiteGraphSpec
Specification "PublishSiteGraphSpec"
  specifies
  <strong>o </strong>directories are nodes
    <strong>Won't work until MemoryResourceRepository adds resources for directories.</strong>
    (PublishSiteGraphSpec.scala:19)

Total for specification "PublishSiteGraphSpec":
Finished in 0 second, 54 ms
1 example (1 skipped), 0 assertion, 0 failure, 0 error</pre>
<p>Ok, let's move on with the next spec:</p>
<pre>class MemoryRepositorySpecTest extends JUnit4(MemoryRepositorySpec)
object MemoryRepositorySpec extends Specification {
  "directories are resources" in {
    val repository = new MemoryResourceRepository()
    repository.importResource("directory/name.ext",
                              new StringResource("directory/name.ext", "the content"))
    repository.getResource("directory") must haveClass(classOf[DirectoryResource])
  }
}</pre>
<p>And a familiar failure is seen:</p>
<pre><span style="color:#ff0000;">The file "directory" does not exist
</span></pre>
<h2>Time to implement</h2>
<p>Firstly break break the path into path-elements</p>
<pre>override def defineResource(name:String):OutputStream = {
  val path = name.split("[\\/]")
<span style="color:#3366ff;"><em>  </em><span style="color:#000000;">createDirectory</span></span>Recources<span style="color:#3366ff;"><span style="color:#000000;">(path.toList)</span></span>
<em>  ...
</em>}</pre>
<p>Secondly, define the method that creates the directories. All but the last elements are assumed to be directories. Therefore we use the <em>dropRight(n:Integer)</em> function before we iterate the path-elements. Note how we can pass the function <em>createDirectoryResource(name:String)</em> as an  argument to <em>foreach</em>.</p>
<pre>private def createDirectoryRecources(elements:List[String]) =  {
  elements.dropRight(1).foreach(createDirectoryNode)
}</pre>
<p>Thirdly we implement the createDirectoryResource function. Here we use the <em>getOrElseUpdate</em> function on the mutable <em>Map</em>. The <em>getOrElseUpdateMethod</em> simply looks for an element in the map, if the element exists it is returned, if the element does not exist it is created by the function passed in the second argument and returned.</p>
<p>We don't really care about the value here, we just use the second argument as an event to create directories that do not exist.</p>
<pre>private def createDirectoryRecource(name:String):Resource =  {
  resources.getOrElseUpdate(name, {new DirectoryResource(name)})
}</pre>
<p>We run the specs again:</p>
<pre>Specification "PublishSiteGraphSpec"
  specifies
  o directories are nodes
    Won't work until MemoryResourceRepository adds resources for directories. (PublishSiteGraphSpec.scala:19)

Total for specification "PublishSiteGraphSpec":
Finished in 0 second, 87 ms
1 example (1 skipped), 0 assertion, 0 failure, 0 error

Running java com.agical.publisher.resource.memory.MemoryRepositorySpec
Specification "MemoryRepositorySpec"
  specifies
  + directories are resources

Total for specification "MemoryRepositorySpec":
Finished in 0 second, 149 ms
1 example, 1 assertion, 0 failure, 0 error</pre>
<p>While MemoryResourceRepository does not work as we want it to work yet we can at least make the PublishSiteGraphSpec treat directories as nodes. So we remove the skip-statement and get the following error</p>
<pre>Specification "PublishSiteGraphSpec"
  specifies
  x directories are nodes
    'com.agical.publisher.content.core.CopyNode@1f934ad'
    doesn't have class 'com.agical.publisher.content.core.DirectoryNode'
    but 'com.agical.publisher.content.core.CopyNode' (PublishSiteGraphSpec.scala:24)</pre>
<p>Now the graph finds the directory resource but does not create a <em>DirectoryNode</em> but a <em>CopyNode</em>.</p>
<p>We jo-jo up and down in the code skipping as necesary until the SiteGraph-test passes and, implicitly, no skips remain.</p>
<p><em>We never specify something that is not driven by a need that can be traced back to our </em><em>outer spec. Therefore when the </em><em>outer spec works, by definition, no more skips remain. This is called outside in and is one of signifying aspects of BDD.</em></p>
<h2>Making the spec into a contract</h2>
<p>Now I find myself in the position where my specs pass but my userguide does not. I have made all the changes for MemoryResourceRepository and would like to make the same changes work for the FileSystemRepository. I need some way to test the same contract on both implementations.</p>
<p>Luckily specs provides a way:</p>
<pre>class ResourceRepositoryTest extends JUnit4(ResourceRepositorySpec)
object ResourceRepositorySpec extends Specification {
  implicit def javaIterableToScalaIterable[T](iterable:java.lang.Iterable[T]):Iterable[T] = {
    new Iterable[T] {
      override def elements = {
        val iterator = iterable.iterator();
        new Iterator[T] {
          override def next = iterator.next()
          override def hasNext = iterator.hasNext()
        }
      }
    }
  }

  val root = getClass().getResource("/");
<strong>  commonSpecs(new MemoryResourceRepository())
  commonSpecs(new FileResourceRepository(new File(new File(root.toURI), "test")))

  def commonSpecs(repository:ResourceRepository) = {
</strong>    val oneResourceInOneDirectory = beforeContext {
      repository.importResource("directory/name.ext", new StringResource("directory/name.ext", "the content"))
    }
	"A "+ repository.getClass().getSimpleName +" with one resource in one directory" -&#62;-(oneResourceInOneDirectory) should {
      "create directory resources for directories" &#62;&#62; {
        repository.getResource("directory") must haveClass(classOf[DirectoryResource])
      }
      "create regular resources for resources" &#62;&#62; {
        val resource = repository.getResource("directory/name.ext")
        resource.getName mustNot haveClass(classOf[DirectoryResource])
      }
      "the directory resource must " &#62;&#62; {
        val directory = repository.getResource("directory") match { case directory:DirectoryResource =&#62; directory}
        "be named after the directory" &#62;&#62; {
          directory.getName must beEqual("directory")
        }
      }
    }
  }
}</pre>
<p>I simply wrap my specs in a method-definition and I pass the repository of choice as a parameter to my definition. Not too bad. The downside is that I now have a dependency to two different implementations from my <em>contract-spec</em>. The logical dependency direction would be the opposite in my opinion.</p>
<p>I'm on my way to be productive with specs. I'm still struggling a bit with how I should structure my specs but I think it is...</p>
<h2>Time to wrap up with some final thoughts on specs</h2>
<p>Specs does not impress me in the same way as rspec did. While most things seem to be possible it fails to guide me correctly. The documentation is pretty much features piled on top of features and it's sometimes hard to figure out when I would use one feature over the other. Moreover, rspec just seems to do the most logical thing with a minimum of effort while specs allows me to do the most logical thing with <em>some</em> effort. Also specs naming seems a bit awkward</p>
<p>Compare rspec's:</p>
<pre>describe Account, " when first created" do
  it "should have a balance of $0"
end</pre>
<p>that gives the output:</p>
<pre>Account when first created
- should have a balance of $0 (PENDING: Not Yet Implemented)

Pending:
Account when first created should have a balance of $0 (Not Yet Implemented)

Finished in 0.007737 seconds
1 example, 0 failures, 1 pending</pre>
<p>With specs:</p>
<pre>package com.agical.publisher.resource
import org.specs._

object AccountSpec extends Specification {
  "Account when first created" should {
    "have a balance of $0" in {
      skip("PENDING: not yet implemented")
    }
  }
}</pre>
<p>That outputs:</p>
<pre>Specification "AccountSpec"
  Account when first created should
  o have a balance of $0
    PENDING: not yet implemented (AccountSpec.scala:8)

Total for specification "AccountSpec":
Finished in 0 second, 64 ms
1 example (1 skipped), 0 assertion, 0 failure, 0 error</pre>
<p>The major thing to note is that rspecs that don't have a body become pending by default. Specs that don't have a body just pass and you can optionally add a skip statement with a description to achieve the same thing. I have this feeling in general that where rspec is very thought through specs seems to have more of a spray and pray attitude towards features. Ok, that's a bit harsh, specs is not bad, it's just not much more than <em>ok</em> in my book.</p>
<p>It's quite possible that I missed some nuggets in specs due to my expectations formed by rspec and I will continue to use specs since I think it is good enough for my needs.</p>
<p>Pfewww, that turned out to be quite a beast of a post. I'll try to keep them shorter in the future...</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Partial mocking of objects using easymock classextensions]]></title>
<link>http://tejakantamneni.wordpress.com/2008/09/11/partial-mocking-of-objects-using-easymock-classextensions/</link>
<pubDate>Thu, 11 Sep 2008 23:34:00 +0000</pubDate>
<dc:creator>tejakantamneni</dc:creator>
<guid>http://tejakantamneni.th.wordpress.com/2008/09/11/partial-mocking-of-objects-using-easymock-classextensions/</guid>
<description><![CDATA[Ocassionally, some of your methods in your classes need to call some other public methods in the sam]]></description>
<content:encoded><![CDATA[<p>Ocassionally, some of your methods in your classes need to call some other public methods in the same class to get the job done. But when writing unit tests for the calling methods, you want to keep your tests isolated from the calls to other public methods. I encountered such a scenario recently and found that Easymock can help you by mocking some of the methods while keeping the rest of the methods intact.</p>
<p>Let us see an example,<br />
The BlogSearchService has two public methods, first method filterBlogsByAuthor takes an author name and a list of blogs and returns all the blogs written by that particular order author.<br />
The other business method searchBlogs will take a search paramter and the author, it will get all the blogs by the search parameter using a custom logic and do some other house keeping tasks like sorting them by published date and number of comments and then filter the methods by author.</p>
<pre style="width:500px;font-family:courier new;font-size:12px;padding:0 0 20px;"><span style="color:blue;">package</span> com.teja.blogs;

<span style="color:blue;">import</span> <span style="color:olive;">java</span>.<span style="color:olive;">util</span>.<span style="color:olive;">Collections</span>;<span style="color:blue;">import</span> <span style="color:olive;">java</span>.<span style="color:olive;">util</span>.<span style="color:olive;">List</span>;

<span style="color:green;">/**** @author Teja*/</span><span style="color:blue;">public</span> <span style="color:blue;">class</span> BlogSearchService {

      <span style="color:blue;">public</span> <span style="color:olive;">List</span>&#60;Blog&#62; searchBlogs(<span style="color:olive;">String</span> searchString, <span style="color:olive;">String</span> author){

              <span style="color:green;">//do some custom logic here on these blogs like sorting them by posted date.</span>              <span style="color:blue;">return</span> filterBlogsByAuthor(author, <span style="color:olive;">Collections</span>.EMPTY_LIST);      }

      <span style="color:blue;">public</span> <span style="color:olive;">List</span>&#60;Blog&#62; filterBlogsByAuthor(<span style="color:olive;">String</span> author, <span style="color:olive;">List</span>&#60;Blog&#62; blogs){
             <span style="color:blue;">return</span> <span style="color:olive;">Collections</span>.EMPTY_LIST;
 }

}</pre>
<p>When writing the test cases for the second method, I don't want to test the other public method filterByAuthor as<br />
(i)it has already been tested by other test cases,<br />
(ii)I want to keep my test cases more unit.</p>
<p>So in my test case where I am testing my searchBlogs, I am creating the mock service class which has mock methods only for filterBlogsByAuthor, but the actual mehtod(searchBlogs) which is about to be tested is not.<br />
As usual you can do expectations on the mock class, replay and verify as if it is some other external resource being mocked.</p>
<p>To create a partial mock class of the service, the extra parameter you need to pass is the name of the method to be mocked and the parameter types it accepts (coz, it need to know which version of the  method you want to mock if you have overloaded methods)</p>
<p>Here is our test class:</p>
<pre style="overflow:auto;width:500px;font-family:courier new;font-size:12px;padding:0 0 20px;"><span style="color:blue;">package</span> com.teja.blogs;

<span style="color:blue;">import</span> <span style="color:olive;">java</span>.<span style="color:olive;">util</span>.<span style="color:olive;">Collections</span>;<span style="color:blue;">import</span> <span style="color:olive;">java</span>.<span style="color:olive;">util</span>.<span style="color:olive;">List</span>;<span style="color:blue;">import</span> <span style="color:olive;">org</span>.junit.Test;<span style="color:blue;">import</span> <span style="color:olive;">org</span>.easymock.classextension.EasyMock;

<span style="color:green;">/**** @author Teja*/</span><span style="color:blue;">public</span> <span style="color:blue;">class</span> BlogSearchServiceTest {

        @Test        <span style="color:blue;">
public</span> <span style="color:blue;">void</span> testSearchBlogs() <span style="color:blue;">throws</span> <span style="color:olive;">NoSuchMethodException</span> {
 <span style="color:olive;">String</span> author = "<span style="color:magenta;">Teja</span>";
BlogSearchService blogSearchService =
EasyMock.createMock(BlogSearchService.<span style="color:blue;">class</span>,BlogSearchService.<span style="color:blue;">class</span>.getMethod("<span style="color:magenta;">filterBlogsByAuthor</span>", <span style="color:blue;">
new</span> <span style="color:olive;">Class</span>[]{<span style="color:olive;">String</span>.<span style="color:blue;">class</span>, <span style="color:olive;">List</span>.<span style="color:blue;">class</span>}));
EasyMock.expect(blogSearchService.filterBlogsByAuthor(author, <span style="color:olive;">Collections</span>.EMPTY_LIST)).andReturn(<span style="color:olive;">Collections</span>.EMPTY_LIST);                EasyMock.replay(blogSearchService);                blogSearchService.searchBlogs("<span style="color:magenta;">easymock</span>", author);                EasyMock.verify(blogSearchService);        }

}</pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Phasing over from java to scala pt. 3 - What about the tests?]]></title>
<link>http://johlrogge.wordpress.com/?p=50</link>
<pubDate>Wed, 10 Sep 2008 21:44:41 +0000</pubDate>
<dc:creator>johlrogge</dc:creator>
<guid>http://johlrogge.th.wordpress.com/2008/09/10/phasing-over-from-java-to-scala-pt-3-what-about-the-tests/</guid>
<description><![CDATA[I&#8217;ve now spent some time every now and then converting Java-classes into Scala classes. I]]></description>
<content:encoded><![CDATA[<p>I've now spent some time every now and then converting Java-classes into Scala classes. I'm one of those Agile loudmouths so some of you may wonder what I'm doing about the tests. I mentioned that all tests pass in <a href="http://johlrogge.wordpress.com/2008/09/02/phasing-over-from-java-to-scala-pt-2-buildr/">pt. 2</a> but I have not written about how I test. Well, it probably comes as no surprise that the current code is tested in JUnit and I have simply kept my old test-suite intact when phasing over. This strategy works well since what I'm really doing is refactoring. I move class by class in baby steps, running my tests after each change to make sure that everything is still working as it should. But I'm starting to be done with the move now and a strategy for writing new scala-code seems more and more relevant.</p>
<p><!--more--></p>
<h3>What does Buildr support?</h3>
<p>Since I'm building with <a href="http://incubator.apache.org/buildr/">Buildr</a> I would need a really good reason to go with something that Buildr can't handle. Let's have a look at what our options are:</p>
<blockquote><p>Buildr supports three Scala testing frameworks:   <a href="http://www.artima.com/scalatest">ScalaTest</a>,  <a href="http://code.google.com/p/scalacheck/">ScalaCheck</a> and  <a href="http://code.google.com/p/specs/">Specs</a>. Scala testing is automatically enabled if you have any <code>.scala</code> source files under <code>src/test/scala</code>.</p>
<p>...</p></blockquote>
<p>Ok, ScalaTest, ScalaCheck and Specs in any combination. Choices, choices... After looking around in the documentation from all three frameworks I found the following:</p>
<ul>
<li>Scala Check is a scala variant of QuickCheck for Haskell. Scala Check is supported by both ScalaTest and Specs</li>
<li>ScalaTest seems to me to be a rather traditional xUnit-style testing-framework. There are a few unusual constructs such as the FunSuite that uses functions instead of test-prefixed method-names to identify tests but in general ScalaTest feels like familiar territory with a few exotic flowers around.</li>
<li>Specs is similar to rspec for Ruby and claims to be a BDD framework.</li>
</ul>
<p>Both specs and Scala Test have JUnit-support which allows me to run my tests from JUnit. While this may not seem like a big deal at first it does give tremendous value when working with mixed code like I do, I can run all my tests/specs using the same JUnit-tool, this limits task switching and frankly improves the likeliness that I will run my tests/specs as frequently as I should.</p>
<p>Scala Check seems interesting to me since I have been playing witht JUnit 4.4 theories. I'm glad it's available in both frameworks so that my choice is not limited  by that aspect.</p>
<p>I think I will take specs for a spin since I am a fan of rspec and BDD, I'm also curious how an rspec inspired tool would look in scala, it's bound to do things that can't be done in java. So more for me to learn that way seems to be the verdict.</p>
<p>Ok,</p>
<p>Through <a href="http://danielbrolund.wordpress.com/2008/08/23/user-guide-driven-development/">UGDD</a> I have come to the conclusion that I need to add some features to the SiteGraph. I need to represent directories as nodes in the graph.</p>
<h3>Installing specs</h3>
<blockquote><p>If you're a Maven user, you need to add the following dependency to your pom file:</p>
<pre>    &#60;dependency&#62;
      &#60;groupId&#62;org.specs&#60;/groupId&#62;
      &#60;artifactId&#62;specs&#60;/artifactId&#62;
      &#60;version&#62;1.3.0&#60;/version&#62; &#60;!-- specify the version here -&#62;
    &#60;/dependency&#62;</pre>
</blockquote>
<p>In buildrish this translates to</p>
<pre>SPECS = group("specs", :under=&#62;"org.specs" :version=&#62;"1.3.1")</pre>
<p>It turns out that we also have to add the scala tools repository to our buildfile. I did not find that information on the site, perhaps this is already done in maven or it's so obvious that everyone that worked more than 2 days with scala is aware of that. This is how you add the repository to you buildfile:</p>
<pre>repositories.remote &#60;&#60; "http://www.agical.com/maven2/"
                    &#60;&#60; "http://www.ibiblio.org/maven2/"
                    &#60;&#60; "http://repo1.maven.org/maven2/"
                    <strong>&#60;&#60; "http://scala-tools.org/repo-releases"</strong></pre>
<p>In order to run compile and run with specs we also need to add the following two lines to our buildfile in our scala-project:</p>
<pre>test.compile.with SPECS
test.with SPECS</pre>
<p>Ok, we're all set... let's write the first spec. Buildr dictates that we should put our specs in <em>src/test/scala</em> and name them according to the <em>&#60;SpecName&#62;Spec.scala</em> pattern.</p>
<p>Said and done, behold the first specification:</p>
<pre>package com.agical.publisher.content.site
import org.specs._

object PublishSiteGraphSpec extends Specification {
  "directories are nodes" in {}
}</pre>
<p>And now run it with buildr:</p>
<pre>Testing publisher:scala-core
Compiling publisher:scala-core:test into /home/jocke/dev/publisher/scala-core/target/test/classes
Running tests in publisher:scala-core
Running java com.agical.publisher.content.site.PublishSiteGraphSpec
Specification "PublishSiteGraphSpec"
  specifies
  + directories are nodes</pre>
<p>Ok, I don't know about you but switching between a command window and eclipse annoys me. Let's see what I can do about that...</p>
<h3>Running via JUnit from eclipse</h3>
<p>Lets see how well the promised JUnit integration actually works. It turns out that the JUnit support is all but satisfying :(</p>
<p>It starts ok:</p>
<pre>package com.agical.publisher.content.site
import org.specs._
import org.specs.runner._

class PublishSiteGraphSpecTest extends JUnit4(PublishSiteGraphSpec)
object PublishSiteGraphSpec extends Specification {
  "directories are nodes" in {}
}</pre>
<p>All I have to do is to add a class that extends JUnit4. I don't find this much more annoying than having to add the <em>@Runwith(Theories)</em> annotation in JUnit4 when testing with theories.</p>
<p>Now to the ugly part:In order to be able to select your JUnit4 classes, you need to add the output directory of your project to your build path:</p>
<ol>
<li>Select your project</li>
<li> Go to "Build Path / Configure Build Path"</li>
<li> In the "Libraries" tab, "Add Class Folder"</li>
<li>In the "Class Folder Selection" dialog, do "Create New Folder"</li>
<li> In the "New Folder" dialog, select "Advanced" and "Link to folder in the file system"</li>
<li> Select the output folder of your project</li>
<li>Refresh your project (F5 on the project's folder)</li>
</ol>
<p>You should now be able to select the JUnit4 classes of your Scala project.</p>
<p>Quite a turnoff but...</p>
[caption id="attachment_54" align="alignnone" width="300" caption="It works!"]<a href="http://johlrogge.wordpress.com/files/2008/09/specs_eclipse.png"><img class="size-full wp-image-54" title="Specs eclipse" src="http://johlrogge.wordpress.com/files/2008/09/specs_eclipse.png" alt="It works!" width="300" height="503" /></a>[/caption]
<p>It works!!!</p>
<p>But when I try to run builder again the following error greets me:</p>
<pre>Compiling publisher:scala-core:test into /home/jocke/dev/publisher/scala-core/target/test/classes
NoClassDefFoundError: junit/framework/Test
rake aborted!
junit/framework/Test</pre>
<p>Obviously I have forgotten to put JUnit on the test-classpath. Said and done:</p>
<pre>test.compile.with [JUNIT4, SPECS]
test.with [JUNIT4, SPECS, LOGBACK]</pre>
<p>But the error is still there!!! This is kind of bad, people have enough resistance to automatic specification and tests as it is, getting them to run should be easy!</p>
<p>Ok, I am curious, what is going on here? Running Buildr with --trace gives the following extra information:</p>
<pre>** Execute publisher:scala-core:test:setup
** Execute publisher:scala-core:test
NoClassDefFoundError: junit/framework/Test
** Invoke publisher:scala-core:test:teardown (first_time)
** Execute publisher:scala-core:test:teardown
rake aborted!
junit/framework/Test
/var/lib/gems/1.8/gems/buildr-1.3.2/lib/buildr/java/test_frameworks.rb:68:in `method_missing'
/var/lib/gems/1.8/gems/buildr-1.3.2/lib/buildr/java/test_frameworks.rb:68:in `filter_classes'
/var/lib/gems/1.8/gems/buildr-1.3.2/lib/buildr/java/test_frameworks.rb:363:in `tests'
/var/lib/gems/1.8/gems/buildr-1.3.2/lib/buildr/core/test.rb:423:in `run_tests'
/var/lib/gems/1.8/gems/buildr-1.3.2/lib/buildr/core/test.rb:196:in `initialize'</pre>
<p>Ok, not that it tells me a lot but I bet that peeking into <em>test_frameworks.rb</em> will. It does not show in this blog but days have passed and I have considered jst going with scala-test instead or possibly the combination of specs and scala-test but I stubbornly refuse to give up even though I should. I tell myself that I might learn a thing or two about Buildr.</p>
<p>After getting my hands dirty I find the following on line <em>308</em>:</p>
<pre>      # ScalaTest dependencies
      DEPENDS = ["org.scalatest:scalatest:jar:#{VERSION}"] +
                 JMock::REQUIRES +
                 ScalaSpecs::REQUIRES +
                 ScalaCheck::REQUIRES</pre>
<p>A simple <em></em></p>
<pre>+  JUnit::REQUIRES</pre>
<p>Solves the issue:</p>
<pre>Running tests in publisher:scala-core
Running java com.agical.publisher.content.site.PublishSiteGraphSpec
Specification "PublishSiteGraphSpec"
  specifies
  + directories are nodes
Total for specification "PublishSiteGraphSpec":
Finished in 0 second, 72 ms
1 example, 0 assertion, 0 failure, 0 error</pre>
<p>And I can go on to make the specification fail.</p>
<p>Up until this part phasing over to Scala has been a smooth ride. Specs offered some ugly hack to make it work in eclipse,but it woks. Buildr gave me a really hard time and I spent hours literally before I decided it was time to patch Buildr itself. Buildr has on the other hand been a very friendly companion up until this time and I assume that the combination Buildr, Scala, Specs + JUnit has been that common so far. On the other hand, if this was ant or maven I would have had a <em>much</em> harder time patching the tool. It makes a certain kind of sense to build with a dynamic language, to me anyway.</p>
<p>In the next part we will make our specification fail.</p>
<p>I'll leave you with that until next time...</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Test Coverage Report for CDK Nightly]]></title>
<link>http://rguha.wordpress.com/?p=63</link>
<pubDate>Mon, 08 Sep 2008 03:40:11 +0000</pubDate>
<dc:creator>Rajarshi Guha</dc:creator>
<guid>http://rguha.th.wordpress.com/2008/09/08/test-coverage-report-for-cdk-nightly/</guid>
<description><![CDATA[I just updated the CDK Nightly build script so that it summarizes the state of unit test coverage. C]]></description>
<content:encoded><![CDATA[<p>I just updated the <a href="http://cheminfo.informatics.indiana.edu/~rguha/code/java/nightly/" target="_blank">CDK Nightly</a> build script so that it summarizes the state of unit test coverage. Currently, trunk has a total of 3215 methods (in 378 classes) that are missing unit tests. See the <a href="http://cheminfo.informatics.indiana.edu/~rguha/code/java/nightly/junitsummary.html" target="_blank">JUnit test summary</a> for a module-wise summary.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The same, but different]]></title>
<link>http://lizdouglass.wordpress.com/2008/09/06/the-same-but-different/</link>
<pubDate>Sat, 06 Sep 2008 06:16:00 +0000</pubDate>
<dc:creator>lizdouglass</dc:creator>
<guid>http://lizdouglass.th.wordpress.com/2008/09/06/the-same-but-different/</guid>
<description><![CDATA[Recently I’ve been using JUnit. In keeping with the most up to date libraries, we upgraded our pro]]></description>
<content:encoded><![CDATA[<p>Recently I’ve been using JUnit. In keeping with the most up to date libraries, we upgraded our project this week to JUnit 4.4 to JUnit 4.5 and that’s where we encountered a hiccup….</p>
<p>In our project, we are interested in doing specific things if a test has failed. For the purposes of demonstration, lets suppose that we want to output the test name to the console when a test fails (using a method annotated with @After). How do we know whether a test has failed or not? We can access this information by using a custom test runner that extends the JUnit4ClassRunner (in JUnit 4.4), like this one ...</p>
<pre>public class MyTestRunner
   extends JUnit4ClassRunner
{
   private static String
     failureMessage = null;

   public static String getFailureMessage() {
      return failureMessage;
   }

   public MyTestRunner(Class klass)
      throws InitializationError
   {
      super(klass);
   }

   public void run(final RunNotifier notifier) {
      failureMessage = "";
      notifier.addListener(new FailureListener());
      super.run(notifier);
   }

   private class FailureListener
      extends RunListener {

      public void testFailure
        (Failure failure) throws Exception {
           failureMessage = failure.getTestHeader();
        }
      }
}</pre>
<p>Our runner (above) overrides the run method (only) so that we can add a FailureListener to the RunNotifier. As per the observer pattern, our notifier will call the testFailure method if the test fails, thereby setting the failureMessage. We can access the failure message from our @After method like this...</p>
<pre>@RunWith(MyTestRunner.class)
public class MyClassTest
{
   @After
   public void printRunStatusMessage()
   {
      if (!MyTestRunner.getFailureMessage().equals(""))
         System.out.println(MyTestRunner.getFailureMessage());
      else
         System.out.println("Test did not fail");
   }

   @Test
   public void shouldAssertTruth() throws Exception
   {
      assertEquals(true, false);
   }
}</pre>
<p>Note that our test class is annotated with @RunWith(MyTestRunner.class) - meaning that we are running the tests using our custom runner. If we go ahead and run the shouldAssertTruth test we get this line printing to the console "shouldAssertTruth(com.thoughtworks.blogdemo.test.MyClassTest)". Ta da!</p>
<p>In the migration to JUnit 4.5, we discovered that JUnit4ClassRunner is now deprecated. It has been replaced with the new BlockJUnit4ClassRunner. According to <a href="http://junit.sourceforge.net/javadoc_40/index.html">the JUnit API documentation</a> the BlockJunit4ClassRunner "should have exactly  the same behavior as the old test class runner (<code>JUnit4ClassRunner</code>)". By simply substituting the old runner class with the new one and re-executing the shouldAssertTruth test we get (drumroll) "Test did not fail" output to the console... hmm, that's not expected....</p>
<p>In JUnit 4.4 there are calls to an addFailure method scattered throughout the code that executes the @Before, @Test and @After annotated methods for each test. This is what the addFailure method looks like:</p>
<pre>protected void addFailure(Throwable e) {
   fNotifier.fireTestFailure
      (new Failure(fDescription, e));
}</pre>
<p>This method lets us know immediately when a test has failed and is the reason why our custom runner worked so well. In JUnit 4.5 we now have the concept of Statements, and without going into detail about them, JUnit now has a RunAfters class. This class is used when we want to run a test and execute its associated @After methods. The class looks like this...</p>
<pre>public class RunAfters extends Statement {
   private final Statement fNext;
   private final Object fTarget;
   private final List fAfters;

   public RunAfters(Statement next,
      List afters,
      Object target) {
         fNext= next;
         fAfters= afters;
         fTarget= target;
   }

   @Override
   public void evaluate() throws Throwable {
      List fErrors = new ArrayList();
      fErrors.clear();
      try {
         fNext.evaluate();
      } catch (Throwable e) {
      fErrors.add(e);
      } finally {
         for (FrameworkMethod each : fAfters)
            try {
               each.invokeExplosively(fTarget);
            }
            catch (Throwable e) {
               fErrors.add(e);
            }
         }
      if (fErrors.isEmpty())
         return;
      if (fErrors.size() == 1)
         throw fErrors.get(0);
      throw new MultipleFailureException(fErrors);
   }
}</pre>
<p>We can see in the evaluate method that any errors that are thrown during the executing of the test are collected in fErrors. fErrors is used at the end of the evaluate method to create and throw a new MultipleFailureException, which will notify our FailureListener. The crucial part for us is that despite an error being thrown during the execution of a test, the @After method will <span style="font-weight:bold;">always</span> be attempted in the finally block, and at that point we are blissfully unaware that the test has failed. Hmph.</p>
<p>Our solution, the quickest one to restore functionality (and not use anything deprecated), has been to create a custom RunAfters class that notifies our FailureListener of any errors in the catch block (see above). It seems less than ideal to have to do this, especially since the changes to the RunAfters class are so minor. Perhaps the next JUnit version will do something else...</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[(J)Unit testing abstract classes and interfaces]]></title>
<link>http://gnoack.wordpress.com/?p=238</link>
<pubDate>Tue, 02 Sep 2008 20:00:27 +0000</pubDate>
<dc:creator>guenthernoack</dc:creator>
<guid>http://gnoack.th.wordpress.com/2008/09/02/junit-testing-abstract-classes-and-interfaces/</guid>
<description><![CDATA[
Note to self: This is how you can unit test abstract classes and interfaces in Java (using the Lisk]]></description>
<content:encoded><![CDATA[<div align="center"><a href="http://gnoack.files.wordpress.com/2008/09/ducks.png"><img src="http://gnoack.wordpress.com/files/2008/09/ducks.png" alt="Liskov substituted ducks" width="400" height="402" class="size-full wp-image-239" /></a></div>
<p>Note to self: This is how you can unit test abstract classes and interfaces in Java (using the <a href="http://c2.com/cgi/wiki?LiskovSubstitutionPrinciple">Liskov substitution principle</a>). Using a Java 5 generic for the type of the concrete class under test to avoid excessive casting seems to be a good idea. (AbstractDuckTest has the generic type T, getDuckUnderTest() returns a T, the concrete subclasses of the test case make T be the concrete tested class.)</p>
<p>In languages with dynamic typing, it doesn't get so complicated. If superclass attributes are accessible from classes below, you don't even need the getter. :-) Implementation becomes trivial then.</p>
<p>See <a href="http://c2.com/cgi/wiki?AbstractTestCases">Ward's wiki: Abstract Test Cases</a> for a more detailed discussion, including code examples in Java.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Test Driven - Lasse Koskela/Manning]]></title>
<link>http://jugcluj.wordpress.com/?p=16</link>
<pubDate>Tue, 02 Sep 2008 08:25:46 +0000</pubDate>
<dc:creator>Ionel Condor</dc:creator>
<guid>http://jugcluj.th.wordpress.com/2008/09/02/test-driven-lasse-koskelamanning/</guid>
<description><![CDATA[
I have read this book a few weeks ago and now I am getting started to really apply it in a project.]]></description>
<content:encoded><![CDATA[<p><!--[if gte mso 9]&#62;  Normal 0   14   false false false  IT X-NONE X-NONE              MicrosoftInternetExplorer4              &#60;![endif]--><!--[if gte mso 9]&#62;                                                                                                                                            &#60;![endif]--></p>
<p class="MsoNormal"><span lang="EN-US">I have read this book a few weeks ago and now I am getting started to really apply it in a project.<br />
In the field of TDD, this book is one of the best books I have ever read.<br />
The book is easy to ready, easy to understand and well-written. </span></p>
<p class="MsoNormal"><span lang="EN-US">The author divided the book in three parts:</span></p>
<p>The first one introduces the concepts/the topics: TDD and Acceptance TDD. It presents an overview of TDD, a nice tutorial that presents you TDD from the ground and even how to apply it to a working code (welcome to refactoring ). Nice introduction to ATDD.<br />
The part is well written and will make you understand very well the concepts.</p>
<p>The second one tries to demonstrate how we can apply TDD in working examples, in working situations so we may say that is entirely a part dedicated to the concrete world of development.<br />
Some key concepts here: fixtures, test doubles, web development (servlets, Spring, JSP, Velocity, Wickets), jdbc database, ORM tools like Hibernate, thread testing , concurrency testing, GUI testing (Swing), tools for GUI testing.<br />
I think the part is a little bit exhaustive, I was getting tired trying to understand all these examples, but anyway it’s a nice reference for all of you that might be interested.</p>
<p>The last part deals with Agile programming /Extreme Programming and presents the concept of building<br />
an entire application in a test-first manner with Acceptance TDD. It presents an application build<br />
properly for such Acceptance TDD named Fit. I think that you have to read also some other books covering this topic in order to be fully documented. I think this part does not covering enough all the concepts behind “write the test first”.</p>
<p>It's important to mention also the appendices: they present JUnit and Easy Mock,<br />
both are well known in the Java world (especially the first one).</p>
<p class="MsoNormal"><span lang="EN-US">I may say that I really love this book, I do not agree entirely with some concepts in the third part of the book but <span> </span>I think that except these points, <span> </span>even if I should read it 10 times I discover every time something new.</span></p>
<p class="MsoNormal"><span lang="EN-US"><br />
</span><a href="http://jugcluj.files.wordpress.com/2008/09/test-driven1.jpg"><img class="aligncenter size-full wp-image-24" src="http://jugcluj.wordpress.com/files/2008/09/test-driven1.jpg" alt="" width="229" height="280" /></a></p>
<p class="MsoNormal"><span lang="EN-US"><span> </span></span></p>
<p class="MsoNormal"><span lang="EN-US"> </span></p>
<p class="MsoNormal"><span lang="EN-US"> </span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Application Test Programmer]]></title>
<link>http://spillerlaszlo.wordpress.com/?p=380</link>
<pubDate>Sun, 31 Aug 2008 11:29:38 +0000</pubDate>
<dc:creator>Spiller László</dc:creator>
<guid>http://spillerlaszlo.th.wordpress.com/2008/08/31/application-test-programmer-2/</guid>
<description><![CDATA[Position Summary:

Be responsible for test activities (plan, automate, report) of specific projects.]]></description>
<content:encoded><![CDATA[<p>Position Summary:</p>
<ul>
<li>Be responsible for test activities (plan, automate, report) of specific projects.</li>
</ul>
<p>Job Responsibilities:</p>
<ul>
<li>Research and adopt new testing processes, tools and technologies.</li>
<li>Document standards and practices and ensure they are introduced across the team and enforced with software engineers.</li>
<li>Document test requirements specifications, design test systems and design tests.</li>
<li>Document test cases and test scripts and programs using the relevant technology e.g. TestDirector or Java and other open source technologies.</li>
<li>Hold bug review meetings</li>
</ul>
<p>Qualifications for Position:</p>
<ul>
<li>Technical Degree</li>
<li>Specific Skills Required</li>
<li>Good understanding of web: http, HTML, JavaScript, Flash, Browsers</li>
<li>Software development and test life cycle.</li>
<li>Structured Testing background.</li>
<li>TestDirector ( Quality Center ) or similar test management and defect tracking tool</li>
<li>Good communication skills in English</li>
<li>Willingness to work alone and with remote teams</li>
<li>Must be proactive and be willing to take the lead with managing the test process over multiple international locations</li>
</ul>
<p>Necessary Experience:</p>
<ul>
<li>2+ years structured testing experience.</li>
<li>Test automation experience of web applications</li>
<li>JUnit experience</li>
</ul>
<p>Desirable Experience:</p>
<ul>
<li>Performance/Load Testing experience is an advantage</li>
<li>Experience in VBScript</li>
</ul>
<p><a href="mailto:laszlo_spiller@kellyservices.hu">laszlo_spiller@kellyservices.hu</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Writing a parameterized JUnit test]]></title>
<link>http://ourcraft.wordpress.com/?p=592</link>
<pubDate>Wed, 27 Aug 2008 14:17:21 +0000</pubDate>
<dc:creator>danielmeyer</dc:creator>
<guid>http://ourcraft.th.wordpress.com/2008/08/27/writing-a-parameterized-junit-test/</guid>
<description><![CDATA[JUnit 4 supports parameterized tests.  There are a few things that confuse me about how you set up ]]></description>
<content:encoded><![CDATA[<p><a href="http://www.testearly.com/2007/04/13/take-heed-of-mixing-junit-4s-parameterized-tests/">JUnit 4 supports parameterized tests</a>.  There are a few things that confuse me about how you set up your test class for it, though.  Let's see what it would look like if what we wanted was to run the same test class, using a different Map&#60;String,String&#62; of settings each time.</p>
<h2>The Normal Things</h2>
<p>There are some elements of setup for using the parameterized test that didn't confuse me.  Let's briefly list them:</p>
<ul>
<li>The test class needs to be decorated with the <code>@RunWith(Parameterized.class)</code> annotation</li>
<li>You need a <code>public</code> <code>static</code> data-providing method, decorated with the <code>@Parameters</code> annotation</li>
<li>Each test method is decorated with @Test (as usual)</li>
</ul>
<h2>Things I Found Confusing</h2>
<h3>The Data-Providing Method's Return Type</h3>
<p>The data-providing @Parameters method has to return a Collection&#60;&#62; of arrays.  Now, ever since at least <a href="http://www.olivet.edu/catalog/3010.htm#o3015">Principles of Programming I &#38; II in college</a>, I've had trouble remembering which subscript is which when you have a multidimensional array.  So when I saw this <a href="http://www.testearly.com/2007/04/13/take-heed-of-mixing-junit-4s-parameterized-tests/">helpful example</a>, my brain got stuck on line 1 of what the @Parameters method was returning:</p>
<p>[sourcecode language='java']<br />
  return Arrays.asList(new Object[][] {<br />
   {"22101", true },<br />
   {"221x1", false },<br />
   {"22101-5150", true },<br />
   {"221015150", false }});<br />
[/sourcecode]</p>
<p>I couldn't think how this would translate to my maps I wanted to run with.</p>
<h3>The Special Constructor</h3>
<p>When you're using the JUnit 4 parameterized test, your test class needs to have a constructor that takes one set of the parameters and stores them to fields in the test class for use during that run.  But I couldn't figure out -- should my constructor expect a Map&#60;String, String&#62;[]?  A Map&#60;String, String&#62;?</p>
<h2>Figuring it Out</h2>
<p>There were a few different facets that it helped me understand:</p>
<h3>Each Element of the Collection is a set of Parameters</h3>
<p>The reason the @Parameters method must return a collection <em>of Arrays</em> is because each Array holds the parameters that are needed for one test scenario.  So if my test class needed a Map, an int, and a boolean, the @Parameters method would return a collection of <em>three-element</em> arrays -- each array containing the parameters for one configuration of the test class.  This leads to the next facet...</p>
<h3>The Test Class Constructor Should Accept One Parameter for Each Element of the Array</h3>
<p>The JUnit parameterized test mechanism expects to instantiate the test class by calling a constructor that has the same number of arguments as there are elements in the current parameters array*.  If my test class FooTest needed a Map, an int, and a boolean each time, the constructor might look something like this:</p>
<p>[sourcecode language='java']<br />
    public FooTest(Map<String, String> map, int value, boolean flag) {<br />
        //...<br />
    }<br />
[/sourcecode]</p>
<p>...and my @Parameters method would need to return a Collection of Arrays of Object ("of Object" since for a given array, the three elements would be of different types).</p>
<p>*I haven't read or tested to see if the JUnit mechanism supports a collection of jagged arrays of configuration parameters such that (for instance) sometimes the test class might be instantiated using the two-arg constructor, other times using its three-arg constructor...</p>
<h3>Store the Parameters in Private Fields in your Test Class</h3>
<p>What you'd normally do is store the parameters you get constructed with to private fields, for use by the @Test methods:</p>
<p>[sourcecode language='java']<br />
@RunWith(Parameterized.class)<br />
class FooTest {<br />
    private Map<String, String> map;<br />
    private int value;<br />
    private boolean flag;</p>
<p>    public FooTest(Map<String, String> map, int value, boolean flag) {<br />
        this.map = map;<br />
        this.value = value;<br />
        this.flag = flag;<br />
    }</p>
<p>    //...<br />
}<br />
[/sourcecode]</p>
<h2>The Application to My Case</h2>
<p>I think I was more confused because I only needed one parameter -- a Map&#60;String, String&#62; -- so it wasn't apparent to me why the Collection of Object <em>Arrays</em> was needed.</p>
<p>So the "hard parts" of my test class end up looking something like this:</p>
<p>[sourcecode language='java']</p>
<p>@RunWith(Parameterized.class)</p>
<p>class FooTest {</p>
<p>    private Map<String, String> map;</p>
<p>    @Parameters<br />
    public static Collection<Object[]> configs() {<br />
        Map<String, String> map1 = new HashMap<String, String>();<br />
        map1.put("Name", "Bill");<br />
        map1.put("Favourite Color", "Blue");</p>
<p>        Map<String, String> map2 = new HashMap<String, String>();<br />
        map2.put("Name", "Sam");<br />
        map2.put("Favourite Color", "Plaid");</p>
<p>        return Arrays.asList(new Object[][] {<br />
                { map1 },<br />
                { map2 }<br />
        });</p>
<p>    public FooTest(Map<String, String> map) {<br />
        this.map = map;<br />
    }</p>
<p>    //...<br />
}<br />
[/sourcecode]</p>
<p>(Maybe nobody else needed that explanation, but it helped me!  :)</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Simple Unit Test With Netbeans 6.1 and JUnit]]></title>
<link>http://linuxgembel.wordpress.com/?p=408</link>
<pubDate>Wed, 27 Aug 2008 04:54:36 +0000</pubDate>
<dc:creator>Kiki Ahmadi</dc:creator>
<guid>http://linuxgembel.th.wordpress.com/2008/08/27/simple-unit-test-with-netbeans-61-and-junit/</guid>
<description><![CDATA[Most people think,
Great God will come from the skies,
Take away everything
And make everybody feel ]]></description>
<content:encoded><![CDATA[<p><em><a href="http://linuxgembel.wordpress.com/files/2008/08/generated-test-class.jpg"></a>Most people think,<br />
Great God will come from the skies,<br />
Take away everything<br />
And make everybody feel high.<br />
But if you know what life is worth,<br />
You will look for yours on earth:<br />
And now you see the light,<br />
You stand up for your rights.<br />
        - Get Up Stand Up, Bob Marley</em></p>
<p>Hi guys! Udah lama gak utak atik java karena project disini pake .NET. Kemaren malam ketika sedang nganggur dan utak atik netbeans bwat ngerefresh pikiran, saya menemukan fitur netbeans keren yaitui automated code generation untuk unit testing menggunakan framewrk JUnit . Just like <a href="http://codinghorror.com" target="_blank"><strong>Jeff Atwood</strong></a> said " A feature is not  a feature until some user used it ",  saya juga baru sadar kemaren klo ada fitur seperti itu di netbeans 6.1. Dengan fitur ini, developer dimudahkan untuk membuat unit test karena Netbeans akan otomatis membuat test class dan test casenya. Lets start coding for further details.</p>
<p>Untuk yang belum familiar dengan unit testing dan JUnit, bisa membaca artikel dibawah ini untuk pendahuluan :</p>
<ul>
<li><strong><a href="http://en.wikipedia.org/wiki/Unit_test" target="_blank">Wikipedia Entry</a></strong></li>
<li><strong><a href="http://endy.artivisi.com/blog/java/ruthless-testing-1/" target="_blank">Blog Pak Endy tentang ruthless testing</a></strong></li>
<li><strong><a href="http://linuxgembel.wordpress.com/2008/02/09/tutorial-first-step-to-junit-4/" target="_blank">Tulisan saya tentang JUnit</a></strong></li>
</ul>
<p>Mari kita mulai dengan membuka netbeans 6.1.</p>
<p><!--more--></p>
<p><strong>Buat sebuah java project baru</strong></p>
<p>Gak wajib sebenarnya, cuman memudahkan aja. Lanjut ke langkah selanjutnya.</p>
<p><strong>Buat class dengan return valued dan void method</strong></p>
<p>Setelah mensetup project netbeans, selanjutnya kita buat class yang berisi return valued method dan void method. Tujuannya adalah melihat hasil generasi kode netbeans terhadap dua method yang berbeda tersebut. Anda juga bisa bereksperimen dengan menggunakan Main method atau method yang mereturn Object. Untuk kali ini, kita buat sangat simple saja. Sebuah class yang berisi operasi dasar matematika.</p>
<p>[sourcecode language='java']</p>
<p>public class SimpleMath {<br />
            <br />
        public int doAddition(int a, int b ){<br />
                                 <br />
            return a + b ;<br />
        }<br />
        public int doSubtraction(int a, int b){<br />
                  <br />
            return a / b;<br />
           <br />
        }<br />
        public void printAddition(int a, int b){<br />
       <br />
                 System.out.println("var1 = "+a+" , var2 = "+b+" " +<br />
                         "hasilnya adalah = "+doAddition(a, b));<br />
                       <br />
        }<br />
    }</p>
<p>[/sourcecode]</p>
<p>Keep the class really really simple karena yang akan kita pelajari disini adalah bagaimana netbeans membuat kode test class secara automatis.</p>
<p><strong>Let the magic do the test code</strong></p>
<p>Pilih menu create Junit test (Tools &#62; Create JUnit test. Setelah itu muncul dialog window yang berfungsi mengatur parameter test class yang dibuat. Setelah itu klik oke dan voila!! test class sudah otomatis dibuat di dalam folder Test Package. Anda juga dapat menggunakan keyboard shortcut Ctrl+Shift + U.</p>
<p><a href="http://linuxgembel.wordpress.com/files/2008/08/netbeans-menu.jpg"><img class="alignnone size-medium wp-image-410" src="http://linuxgembel.wordpress.com/files/2008/08/netbeans-menu.jpg?w=278" alt="" width="278" height="300" /></a></p>
<address><em>Netbeans menu</em></address>
<address></address>
<p><strong>Masukkan parameter test</strong></p>
<p>Edit parameter test pada test class. Sebelum menjalankan test class jangan lupa untuk meremove method <strong>fail()</strong> di masing masing method test case.</p>
<p><strong>Jalankan test class</strong></p>
<p>Jalankan test class pada test package. Palette netbeans unit test akan keluar dan menunjukkan apakah class SimpleMath lolos atau tidak dari unit test.</p>
<p><a href="http://linuxgembel.wordpress.com/files/2008/08/test-result.jpg"><img class="alignnone size-medium wp-image-412" src="http://linuxgembel.wordpress.com/files/2008/08/test-result.jpg?w=300" alt="" width="300" height="111" /></a></p>
<p><em>Test result palette</em></p>
<p>Mudah sekali bukan. Fitur test code generation ini akan sangat membantu karena membuat test case merupakan salah satu pekerjaan yang membosankan dan melelahkan sehingga seringkali dilewatkan oleh developer. With netbeans, its just as simple as pressing Ctrl + shift + U.</p>
<p>Saya juga membuat file .ppt nya in case topik ini akan dipresentasikan entah dimana (heheheh). PPT nya bisa di download di :</p>
<p><a href="http://linuxgembel.wordpress.com/files/2008/08/ppt1.jpg"><img class="alignnone size-medium wp-image-416" src="http://linuxgembel.wordpress.com/files/2008/08/ppt1.jpg?w=300" alt="" width="300" height="224" /></a></p>
<p><strong><a href="http://www.slideshare.net/gembel_linux/simple-unit-testing-with-netbeans-61-presentation/" target="_blank">My Slideshare Account</a> <br />
<a href="http://linuxgembel.wordpress.com/files/2008/08/simple-java-unit-testing-with-junit-4.ppt">simple-java-unit-testing-with-junit-4</a></strong></p>
<p>Sekian dulu temen temen. Have a nice coding day.</p>
<p>:D</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Testing Spring applications with jUnit 4 and Easy Mock]]></title>
<link>http://tejakantamneni.wordpress.com/2008/08/24/testing-spring-applications-with-junit-4-and-easy-mock/</link>
<pubDate>Sun, 24 Aug 2008 03:53:00 +0000</pubDate>
<dc:creator>tejakantamneni</dc:creator>
<guid>http://tejakantamneni.th.wordpress.com/2008/08/24/testing-spring-applications-with-junit-4-and-easy-mock/</guid>
<description><![CDATA[Unit tests help us make sure that the unit chunks of code being developed are correct. Unit test hel]]></description>
<content:encoded><![CDATA[<p>Unit tests help us make sure that the unit chunks of code being developed are correct. Unit test helps find bugs in the early stages of software development.</p>
<p>Java unit testing frameworks like <a href="http://www.junit.org/">jUnit</a>, <a href="http://testng.org/doc/">TestNG</a> with some other pretty frameworks like<a href="http://www.easymock.org/"> easy mock </a>and easy mock class extensions help us test individual classes with mocking out the external dependent classes/resources and make the tests more "unit".</p>
<p>Spring out of the box supports unit testing with jUnit and TestNG. Spring provides seperate set of classes help you unit test your spring classes.</p>
<p>Spring 2.5 in its <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/package-summary.html">org.springframework.test.context</a> package has a set of classes to have better unit testing using jUnit4.</p>
<p>I am about to show an example of testing a service called BlogSearchService. The service simply calls a method in the blogDAO which searches the blogs based on the keyword and return a list of blogs. So here my service class is simple, it calls the DAO. So in my test I just have to make sure that it makes a DAO call and the result is then returned to the client.</p>
<p>Lets see the code for BlogSearchService and BlogSearchServiceImpl,</p>
<p>BlogSearchService.java
<div class="java5 java5" style="border:1px solid rgb(208, 208, 208);color:rgb(0, 0, 102);background-color:rgb(240, 240, 240);font-family:monospace;">
<ol>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">package</span> <span style="color:rgb(0, 102, 153);">com.teja.tests</span>;</div>
</li>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">java.util.List</span>;</div>
</li>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;">/**</span></div>
</li>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> *</span></div>
</li>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> * @author Teja Kantamneni</span></div>
</li>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> */</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> <span style="color:rgb(0, 0, 0);font-weight:bold;">interface</span> BlogSearchService <span style="color:rgb(0, 153, 0);">{</span></div>
</li>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    <span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> List<span style="color:rgb(51, 153, 51);">&#60;</span>Blog<span style="color:rgb(51, 153, 51);">&#62;</span> searchBlogByKeyWord<span style="color:rgb(0, 153, 0);">(</span><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html"><span style="color:rgb(0, 51, 153);font-weight:bold;">String</span></a> keyword<span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 153, 0);">}</span></div>
</li>
</ol>
</div>
<p>BlogSearchServiceImpl.java
<div class="java5 java5" style="border:1px solid rgb(208, 208, 208);font-family:monospace;color:rgb(0, 0, 102);background-color:rgb(240, 240, 240);">
<ol>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">package</span> <span style="color:rgb(0, 102, 153);">com.teja.tests</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">java.util.List</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">org.springframework.beans.factory.annotation.Autowired</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;">/**</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> *</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> * @author Teja Kantamneni</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> */</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> <span style="color:rgb(0, 0, 0);font-weight:bold;">class</span> BlogSearchServiceImpl <span style="color:rgb(0, 0, 0);font-weight:bold;">implements</span> BlogSearchService <span style="color:rgb(0, 153, 0);">{</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    @Autowired</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    BlogDAO blogDAO;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    <span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> List<span style="color:rgb(51, 153, 51);">&#60;</span>Blog<span style="color:rgb(51, 153, 51);">&#62;</span> searchBlogByKeyWord<span style="color:rgb(0, 153, 0);">(</span><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html"><span style="color:rgb(0, 51, 153);font-weight:bold;">String</span></a> keyword<span style="color:rgb(0, 153, 0);">)</span><span style="color:rgb(0, 153, 0);">{</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">        <span style="color:rgb(0, 0, 0);font-weight:bold;">return</span> blogDAO.<span style="color:rgb(0, 102, 51);">searchByKeyword</span><span style="color:rgb(0, 153, 0);">(</span>keyword<span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    <span style="color:rgb(0, 153, 0);">}</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    <span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> <span style="color:rgb(0, 102, 0);font-weight:bold;">void</span> setBlogDAO<span style="color:rgb(0, 153, 0);">(</span>BlogDAO blogDAO<span style="color:rgb(0, 153, 0);">)</span> <span style="color:rgb(0, 153, 0);">{</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">        <span style="color:rgb(0, 0, 0);font-weight:bold;">this</span>.<span style="color:rgb(0, 102, 51);">blogDAO</span> = blogDAO;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">    <span style="color:rgb(0, 153, 0);">}</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 153, 0);">}</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p></ol>
</div>
<p>Here is the test case for BlogSearchService,<br />In the test case, the ContextConfiguration helps in specifying the config file to load. In the @Before (setup method for the test case) I am creating the instance of BlogSearchServiceImpl (but instead you can autowire it). Then I am creating the mock object of blogDAO and setting it to the BlogSearchService.  In the actual test method, I expect that the searchBlogByKeyWord on the blogDAO and I am expecting it retuning no posts. You can do any asserts here depending on the actual business.
<p>  SpringJUnit4ClassRunner is a custom extension of <a href="http://junit.sourceforge.net/javadoc_40/org/junit/internal.runners.JUnit4ClassRunner.html?is-external=true" title="class or interface in org.junit"><code>JUnit4ClassRunner</code></a>  which provides functionality of the <em>Spring TestContext Framework</em>  to standard JUnit 4.4+ tests by means of the <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/TestContextManager.html" title="class in org.springframework.test.context"><code>TestContextManager</code></a> and  associated support classes and annotations.  </p>
<p>
<div class="java5 java5" style="border:1px solid rgb(208, 208, 208);font-family:monospace;color:rgb(0, 0, 102);background-color:rgb(240, 240, 240);">
<ol>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">package</span> <span style="color:rgb(0, 102, 153);">com.teja.tests</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">java.util.Collections</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">org.junit.Before</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">org.junit.Test</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">org.junit.runner.RunWith</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">org.springframework.beans.factory.annotation.Autowired</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">org.springframework.test.context.ContextConfiguration</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">org.springframework.test.context.junit4.SpringJUnit4ClassRunner</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">import</span> <span style="color:rgb(0, 102, 153);">static</span> org.<span style="color:rgb(0, 102, 51);">easymock</span>.<span style="color:rgb(0, 102, 51);">EasyMock</span>.*;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;">/**</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> *</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> * @author Teja Kantamneni</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(102, 102, 102);font-style:italic;"> */</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">@RunWith<span style="color:rgb(0, 153, 0);">(</span>SpringJUnit4ClassRunner.<span style="color:rgb(0, 0, 0);font-weight:bold;">class</span><span style="color:rgb(0, 153, 0);">)</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;">@ContextConfiguration<span style="color:rgb(0, 153, 0);">(</span>locations = <span style="color:rgb(0, 153, 0);">{</span><span style="color:rgb(0, 0, 255);">"classpath:beans.xml"</span><span style="color:rgb(0, 153, 0);">}</span><span style="color:rgb(0, 153, 0);">)</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"><span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> <span style="color:rgb(0, 0, 0);font-weight:bold;">class</span> BlogSearchServiceTest <span style="color:rgb(0, 153, 0);">{</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);font-family:monospace;margin:0;padding:0;"> </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    @Autowired</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    BlogSearchServiceImpl blogSearchService;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    BlogDAO blogDAO;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">            </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    @Before</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    <span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> <span style="color:rgb(0, 102, 0);font-weight:bold;">void</span> setUp<span style="color:rgb(0, 153, 0);">(</span><span style="color:rgb(0, 153, 0);">)</span><span style="color:rgb(0, 153, 0);">{</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        blogSearchService = <span style="color:rgb(0, 0, 0);font-weight:bold;">new</span> BlogSearchServiceImpl<span style="color:rgb(0, 153, 0);">(</span><span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        blogDAO = createMock<span style="color:rgb(0, 153, 0);">(</span>BlogDAO.<span style="color:rgb(0, 0, 0);font-weight:bold;">class</span><span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        blogSearchService.<span style="color:rgb(0, 102, 51);">setBlogDAO</span><span style="color:rgb(0, 153, 0);">(</span>blogDAO<span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    <span style="color:rgb(0, 153, 0);">}</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    </div>
<p></li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    @Test</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    <span style="color:rgb(0, 0, 0);font-weight:bold;">public</span> <span style="color:rgb(0, 102, 0);font-weight:bold;">void</span> testSearchBlogByKeyword<span style="color:rgb(0, 153, 0);">(</span><span style="color:rgb(0, 153, 0);">)</span><span style="color:rgb(0, 153, 0);">{</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html"><span style="color:rgb(0, 51, 153);font-weight:bold;">String</span></a> keyword = <span style="color:rgb(0, 0, 255);">"spring"</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        expect<span style="color:rgb(0, 153, 0);">(</span>blogDAO.<span style="color:rgb(0, 102, 51);">searchByKeyword</span><span style="color:rgb(0, 153, 0);">(</span>keyword<span style="color:rgb(0, 153, 0);">)</span><span style="color:rgb(0, 153, 0);">)</span>.<span style="color:rgb(0, 102, 51);">andReturn</span><span style="color:rgb(0, 153, 0);">(</span><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html"><span style="color:rgb(0, 51, 153);font-weight:bold;">Collections</span></a>.<span style="color:rgb(0, 102, 51);">EMPTY_LIST</span><span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        replay<span style="color:rgb(0, 153, 0);">(</span>blogDAO<span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        blogSearchService.<span style="color:rgb(0, 102, 51);">searchBlogByKeyWord</span><span style="color:rgb(0, 153, 0);">(</span>keyword<span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">        verify<span style="color:rgb(0, 153, 0);">(</span>blogDAO<span style="color:rgb(0, 153, 0);">)</span>;</div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;">    <span style="color:rgb(0, 153, 0);">}</span></div>
</li>
<p>
<li>
<div style="font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;"><span style="color:rgb(0, 153, 0);">}</span></div>
</li>
<p>
<li>
<div style="font-family:monospace;font-weight:normal;font-style:normal;color:rgb(0, 0, 32);margin:0;padding:0;"> </div>
<p></li>
<p></ol>
</div>
<p>It's so simple and sweet testing spring classes with jUnit and easymock. Isn't it?</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring JDBC]]></title>
<link>http://cygni.wordpress.com/?p=211</link>
<pubDate>Tue, 19 Aug 2008 13:25:04 +0000</pubDate>
<dc:creator>Tommy Wassgren</dc:creator>
<guid>http://stacktrace.se/2008/08/19/spring-jdbc/</guid>
<description><![CDATA[Detta inlägg ingår i serien Spring från början och kommer att behandla hur man kan jobba med Jdb]]></description>
<content:encoded><![CDATA[<p>Detta inlägg ingår i serien <a href="http://stacktrace.se/2008/05/30/spring-fran-borjan-introduktion/">Spring från början</a> och kommer att behandla hur man kan jobba med <code>JdbcTemplate</code> och andra centrala klasser i modulen spring-jdbc.</p>
<p><!--more--></p>
<h2>Templating</h2>
<p>Ett designm&#246;nster som används flitigt i Spring &#228;r "template method". En template-metod definierar ett skelett f&#246;r en algoritm. Algoritmen &#228;r abstrakt och det &#228;r upp till subklasser att definiera det konkreta beteendet f&#246;r algoritmen. Ett annat designm&#246;nster som p&#229;minner mycket om "template method" &#228;r m&#246;nstret <a href="http://en.wikipedia.org/wiki/Strategy_pattern" target="_blank">Strategy</a>, en av skillnaderna mellan "template method" och "Strategy" &#228;r att "template method" anv&#228;nder arv medan Strategy-m&#246;nstret anv&#228;nder delegat f&#246;r att uppn&#229; sitt m&#229;l. Nedanst&#229;ende visar anv&#228;ndningen av Strategy-m&#246;nstret via ett exempel som &#228;r kraftigt influerat fr&#229;n ett <a href="http://en.wikipedia.org/wiki/Template_method_pattern" target="_blank">wikipedia-exempel som anv&#228;nder template method</a>.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">/** A game that can be played... */
public interface Game {
    void initializeGame();
    void makePlay(int player);
    boolean endOfGame();
    void printWinner();
} 

/** Concrete implementation of the chess game... */
public class Chess implements Game {
    public void initializeGame() {
        // do chess stuff...
    } 

    public void makePlay(int player) {
        // do chess stuff...
    } 

    public boolean endOfGame() {
        // do chess stuff...
        return false;
    } 

    public void printWinner() {
        // do chess stuff...
    }
} 

/** Concrete implementation of the monopoly game... */
public class Monopoly implements Game {
    public void initializeGame() {
        // do monopoly stuff...
    } 

    public void makePlay(int player) {
        // do monopoly stuff...
    } 

    public boolean endOfGame() {
        // do monopoly stuff...
        return false;
    } 

    public void printWinner() {
        // do monopoly stuff...
    }
} 

/** The class containing the template method. */
public class GameTemplate {
    /**
     * This is a template method that plays the provided
     * game using a specified algorithm (initialize,
     * play, end, print winner)
     *
     * The template method is common to several games in
     * which players play against the others, but only one
     * player is playing at a given time.
     */
    public void play(int playersCount, Game game) {
        game.initializeGame(); 

        int j = 0;
        while (!game.endOfGame()){
            game.makePlay(j);
            j = (j + 1) % playersCount;
        } 

        game.printWinner();
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>Template method</em></strong></td>
</tr>
</tbody>
</table>
<p>Exemplet ovan visar hur en algoritm appliceras på ett <code>Game</code>-objekt i metoden <code>play</code>. Exemplet är en aning förändrat jämfört med originalet så till vida att klassen <code>GameTemplate</code> inte är ett <code>Game</code> utan endast innehåller själva algoritmen för att få en lösare koppling mellan algoritmen och de faktiska <code>Game</code>-objekten.</p>
<p>Nu när vi känner till designmönstret "template method" kan vi kika vidare på templaten som tillhandahålls av Spring för JDBC-relaterade operationer, nämligen <code>JdbcTemplate</code>.</p>
<h2>JdbcTemplate</h2>
<p>Klassen <code>JdbcTemplate</code> är kärnan i den modul som kallas spring-jdbc. Klasserna i denna modul används när access till databasen sker via JDBC snarare än via ett O/R-mappningsramverk såsom Hibernate.</p>
<p>Att använda rå JDBC kan medföra en hel del problem för utvecklaren där Connections, Statements, ResultSets måste stängas, exceptions måste fångas osv. Kod som är skriven för rå JDBC-användning är ofta väldigt utförlig (verbose) och leder lätt till fel (såsom att glömma att stänga ett statement). Springs <code>JdbcTemplate</code> hjälper utvecklaren med många delar av de uppgifter som krävs för att använda JDBC.</p>
<table border="1">
<tbody>
<tr>
<th>Task</th>
<th>Spring</th>
<th>You</th>
</tr>
<tr>
<td>Connection Management</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>SQL</td>
<td></td>
<td>X</td>
</tr>
<tr>
<td>Statement Management</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>ResultSet Management</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Row Data Retrieval</td>
<td></td>
<td>X</td>
</tr>
<tr>
<td>Parameter Declaration</td>
<td></td>
<td>X</td>
</tr>
<tr>
<td>Parameter Setting</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Transaction Management</td>
<td>X</td>
<td></td>
</tr>
</tbody>
</table>
<p>Tabellen ovan visar de delar som <code>JdbcTemplate</code> hjälper dig med jämfört med att använda rå JDBC.</p>
<p>Nedanstående exempel visar vanlig användning av rå JDBC med en enkel parameteriserad SELECT och en mappning mellan ett <code>Person</code>-objekt och ett <code>ResultSet</code>.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">private static final String PERSON_QUERY =
        "select first_name, last_name, phone_number "
        + "from person where last_name = ?"; 

public List getPersonList1() {
    List list = new ArrayList();
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        statement = connection.prepareStatement(PERSON_QUERY);
        statement.setString(1, "Svensson");
        ResultSet rs = statement.executeQuery();
        while (rs.next()) {
            Person person = new Person(
                rs.getString("first_name"),
                rs.getString("last_name"),
                rs.getString("phone_number"));
                list.add(person);
        }
        rs.close();
    } catch (SQLException e) {
        // handle exception somehow...
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // handle exception somehow...
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                // handle exception somehow...
            }
        }
    }

    return list;
}</pre>
</td>
</tr>
<tr>
<td><strong><em>Rå JDBC - getPersonList1</em></strong></td>
</tr>
</tbody>
</table>
<p>Exemplet kan förenklas avsevärt genom användning av <code>JdbcTemplate</code> vilket metoden <code>getPersonList2</code> i nedanstående exempel visar.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public List getPersonList2 () {
    RowMapper personMapper = new RowMapper() {
        // Maps a row to a Person
        public Object mapRow(
                ResultSet rs,
                int rowNum) throws SQLException {

            return new Person(
                rs.getString("first_name"),
                rs.getString("last_name"),
                rs.getString("phone_number"));
        }
    };

    return getJdbcTemplate().query(
        PERSON_QUERY, new Object[] {"Svensson"}, personMapper);
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JdbcTemplate med RowMapper - getPersonList2</em></strong></td>
</tr>
</tbody>
</table>
<p>Vi antar i exemplet ovan att man kan få tag på en <code>JdbcTemplate</code> via metoden <code>getJdbcTemplate()</code>.</p>
<p>Några saker värda att notera:</p>
<ul>
<li>Kod för att hantera connections, statements etc. saknas helt. Detta hanteras av <code>JdbcTemplate</code> som öppnar och stänger alla resurser.</li>
<li>Mappning mellan SQL-resultatet och affärsobjektet sker i en <code>RowMapper</code>. Detta är ett tydligt mönster och <code>RowMapper</code>-objektet kan återanvändas om det deklareras utanför metoden. Förutom <code>RowMapper</code> finns även andra sätt att mappa data och dessa kan återfinnas i Springdokumentationen.</li>
<li>Ingen felhantering krävs. Alla eventuella exceptions fångas av <code>JdbcTemplate</code> och konverteras sedan till Springs egna unchecked exceptions mha. <code>SQLExceptionTranslator</code>. Istället för att kasta ett checked exception med en kryptisk databasunik felkod kan tydliga exceptions såsom <code>BadSqlGrammarException</code> eller <code>OptimisticLockingFailureException</code> kastas. De databaser som supportas out-of-the-box är DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL och Sybase. Naturligtvis går det även att plugga in egna <code>SQLExceptionTranslators</code>.</li>
</ul>
<p>Det finns även några inbyggda <code>RowMappers</code>. Metoden <code>queryForInt</code> som exemplifieras nedan skapar en intern <code>RowMapper</code> där ett SQL-resultat mappas mot ett heltal.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public int countPeople() {
    return getJdbcTemplate().queryForInt(
            "select count(*) from person ");
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JdbcTemplate med queryForInt</em></strong></td>
</tr>
</tbody>
</table>
<p>I exemplen ovan har endast SELECT-frågor mot databasen ställts. Det finns även metoder för att utföra uppdateringar, se exemplet nedan för en enkel parameteriserad uppdatering:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">private static final String UPDATE_PERSON =
    "update person set phone_number = ?"
    + "where first_name = ? and last_name = ?";

public void updatePhoneNumber(
        String firstName, String lastName, String phoneNumber) {

    getJdbcTemplate().update(
            UPDATE_PERSON,
            new Object[] {phoneNumber, firstName, lastName});
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JdbcTemplate med update</em></strong></td>
</tr>
</tbody>
</table>
<p><code>JdbcTemplate</code> behöver endast konfigureras upp med en datakälla. Det finns några bekväma klasser att ärva från för att enkelt få tag på <code>JdbcTemplate</code>-objektet. Klassen <code>JdbcDaoSupport</code> kan användas för DAO-objekt medan klassen <code>AbstractTransactionalDataSourceSpringContextTests</code> fungerar bra för JUnit-tester. Nedanstående exempel visar detta.</p>
<p>Så här kan en DAO-klass se ut:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class MyDao extends JdbcDaoSupport {
    private static final String UPDATE_PERSON =
        "update person set phone_number = ? "
        + "where first_name = ? and last_name = ?";

    public void updatePhoneNumber (
            String firstName, String lastName, String phoneNumber) {

        getJdbcTemplate().update(
                UPDATE_PERSON,
                new Object[] {phoneNumber, firstName, lastName});
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>DAO som ärver JdbcDaoSupport</em></strong></td>
</tr>
</tbody>
</table>
<p>När en DAO konfigureras så måste en <code>DataSource</code> injectas, detta kan exempelvis ske via en JNDI-uppslagning:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean
  id="myDataSource"
  class="org.springframework.jndi.JndiObjectFactoryBean"&#62;

    &#60;property name="lookupOnStartup" value="false" /&#62;
    &#60;property name="proxyInterface" value="javax.sql.DataSource" /&#62;
    &#60;property name="resourceRef" value="true" /&#62;
    &#60;property name="jndiName" value="jdbc/myds" /&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>dataSourceContext.xml</em></strong></td>
</tr>
</tbody>
</table>
<p>Själva DAO-objekten kan exempelvis deklareras i en egen fil som kan användas både för produktion och för test.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean id="myDao" class="se.cygni.sample.spring.template.jdbc.MyDao"&#62;
    &#60;property name="dataSource" ref="dataSource" /&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>daoContext.xml</em></strong></td>
</tr>
</tbody>
</table>
<p>När applikationen ska konfigureras för test så kan en <code>DataSource</code> konfigureras utan JNDI-uppslagning:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean
  id="myDataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource" &#62;

    &#60;property name="driverClassName"
        value="oracle.jdbc.driver.OracleDriver" /&#62;
    &#60;property name="url" value="jdbc:oracle:thin:@host:port:schema" /&#62;
    &#60;property name="username" value="scott" /&#62;
    &#60;property name="password" value="tiger" /&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>testDataSourceContext.xml</em></strong></td>
</tr>
</tbody>
</table>
<p>Ett JUnit-test kan se ut enligt följande:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class MyDaoTest
        extends AbstractTransactionalDataSourceSpringContextTests {

    private MyDao dao;

    protected String[] getConfigLocations() {
        return new String[] {
                "testDataSourceContext.xml",
                "daoContext.xml"
        };
    }

    public void testDao() {
        dao.updatePhoneNumber("Johnny", "Puma", "555-555 5555");

        int count = getJdbcTemplate().queryForInt(
            "select count(*) from person "
            + "where first_name = 'Johnny' "
            + "and last_name = 'Puma' "
            + "and phone_number = '555-555 5555'");

        assertTrue(count == 1);
    }

    public void setMyDao(MyDao dao) {
        this.dao = dao;
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JUnit testfall</em></strong></td>
</tr>
</tbody>
</table>
<p>I testet ovan visas hur dels <code>MyDao</code> injectas i testklassen eftersom filen <code>daoContext.xml</code> anges som en config-location. Även filen <code>testDataSourceContext.xml</code> inkluderas vilket leder till att en <code>DataSource</code> finns tillgänglig och då injectas denna <code>DataSource</code> i basklassen <code>AbstractTransactionalDataSourceSpringContextTests</code> vilket leder till att metoden <code>getJdbcTemplate</code> blir tillgänglig i testfallet.</p>
<p>Det finns även stöd för Java 5 i Springs JDBC modul. Genom att ärva klassen <code>SimpleJdbcDaoSupport</code> istället för <code>JdbcDaoSupport</code> i din DAO kan Java 5 metoder användas via klassen <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html#jdbc-SimpleJdbcTemplate" target="_blank">SimpleJdbcTemplate</a>. Se exemplet nedan.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public List&#60;Person&#62; getPeople() {
    ParameterizedRowMapper&#60;Person&#62; rowMapper =
        new ParameterizedRowMapper&#60;Person&#62;() {
            public Person mapRow(ResultSet rs, int rowNum)
                    throws SQLException {

                return new Person(
                        rs.getString("first_name"),
                        rs.getString("last_name"),
                        rs.getString("phone_number"));
            }
    };

    return getSimpleJdbcTemplate().query(
            "select first_name, last_name, phone_number from person",
            rowMapper);
}</pre>
</td>
</tr>
<tr>
<td><strong><em>SimpleJdbcTemplate</em></strong></td>
</tr>
</tbody>
</table>
<p>För mer information om Spring och JDBC rekommenderas <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html" target="_blank">Springdokumentationen</a> och <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html" target="_blank">JavaDoc för JdbcTemplate</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Agile2008]]></title>
<link>http://ragstorooks.wordpress.com/?p=117</link>
<pubDate>Tue, 19 Aug 2008 07:28:11 +0000</pubDate>
<dc:creator>ragstorooks</dc:creator>
<guid>http://ragstorooks.th.wordpress.com/2008/08/19/agile2008/</guid>
<description><![CDATA[Agile2008 was a huge success. It was a very proud moment for me of course, with it being my first ev]]></description>
<content:encoded><![CDATA[<p><a href="http://www.agile2008.org/">Agile2008</a> was a huge success. It was a very proud moment for me of course, with it being my first ever presentation at a conference. The <a href="http://agile2008toronto.pbwiki.com/Pushing+the+Boundaries+of+Testing+and+Continuous+Integration">talk</a> was well attended with a decent amount of interest for <a href="http://code.google.com/p/testrr/">TestRR</a>.</p>
<p>With around 20 sessions running in parallel for each slot during the conference, it was kind of difficult to choose the session to attend. It was interesting that most of the sessions I went to were small ones, attended by only about 10-12 people and therefore quite interactive. Overall, they were also quite technical in their content and therefore captivated my interest. While talking about it within the team after my return, <a href="http://www.u-phoria.net/blog/">Uros</a> made an insightful comment, "It sounds like you are more interested in the applied engineering aspects of Agile than the tools and practices". I had never thought of it that way but on retrospect, that sounds about right.</p>
<p>I could provide a listing of all the talks I attended but that sounds like overkill. Instead, I will focus on my top three picks:</p>
<h4>TDD in Concurrent Applications by Brett Schuchert &#38; David Nunn</h4>
<p>This was definitely one of the highlights of the conference for me. It became apparent within the first 15 minutes of this 3-hour session that none of the attendees was a novice at understanding and writing concurrent applications, so the session moved on to more advanced discussions quite quickly. While most of the concepts were general, most of the code we looked at was in Java. The two most important bits of advice I took from the session that it is important to actually understand (and read) bytecode to truly understand concurrent code and of the existence of a tool called <a href="http://www.ibm.com/developerworks/java/library/j-contest.html">ConTest</a> which can be used to introduce delays between the execution of consecutive bytecode instructions, thereby increasing the probability of highlighting concurrency issues while testing. Both Brett and David were very impressed by our implementation of an optimistic concurrency control system within our code!</p>
<h4><a href="http://www.tecnicadelpomodoro.it/docs/francesco-cirillo/2007/ThePomodoroTechnique_v1-3.pdf">Pomodoro Technique</a> by Staffan Noteberg</h4>
<p>This was one of the rare slots when I couldn't find anything obviously appealing, so I thought I would try something different. Turned out that going in with an open mind and no prejudices worked well for me and I was able to buy into the idea enough to warrant a trial of it - hopefully sooner rather than later. Essentially, it is a technique that helps you stay focussed on one task for short periods of time, thus enabling you to achieve measurable amounts of work every day. I could clearly see the transposition of the Agile sprint / story idea into a smaller scale, and definitely seems worth a try.</p>
<h4>BDD using JUnit by Dan North &#38; Elizabeth Keogh</h4>
<p>This was my very first session of the conference and it left me feeling positive for the rest of the week. I hadn't realized before the session that Dan was one of the founders of BDD. It was interesting to hear about the origins of BDD and to see a good pairing session which drove home most of their ideas. As an aside, I also found some useful things about <a href="http://www.junit.org/">JUnit4.4</a> and the <a href="http://code.google.com/p/mockito/">Mockito</a> framework. Enough that I would like to try and incorporate them into some real code soon for some first-hand experience.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Junit e SoapUI, strumenti per testare web services]]></title>
<link>http://kaosktrl.wordpress.com/?p=103</link>
<pubDate>Sun, 17 Aug 2008 09:42:28 +0000</pubDate>
<dc:creator>kaosktrl</dc:creator>
<guid>http://kaosktrl.th.wordpress.com/2008/08/17/junit-e-soapui-strumenti-per-testare-web-services/</guid>
<description><![CDATA[In genere durante il processo di sviluppo di una applicazione una delle fasi sottovalutate è quella]]></description>
<content:encoded><![CDATA[<p>In genere durante il processo di sviluppo di una applicazione una delle fasi sottovalutate è quella di testing.</p>
<p>La fase testing dovrebbe in teoria iniziare non appena i requisiti della applicazione sono stati definiti e dovrebbe poi continuare per il tutto il processo di sviluppo poichè all'aumentare della complessità della applicazione i test devono garantirne il suo funzionamento e, dunque, esistono diversi livelli di test da quelli di unità a quelli di sistema e validazione (acceptance test).</p>
<p>Indipendentemente dai livelli esistono test di varia natura da quelli funzionali a quelli di robustezza e performance. In sostanza come avete potuto capire il tutto puo' richiedere abbastanza tempo e quindi se si cerca di rendere quanto più automatica questa fase è meglio.</p>
<p>Nel mondo Java il tutto inizia con le librerie di <a href="http://www.junit.org/" target="_blank">Junit</a>. Rilasciate con licenza Common Public Licence 1.0 sono arrivate, al momento in cui scrivo, alla versione 4.5 (del 8/8/2008). Esse permettono di automatizzare la fase di testing scrivendo metodi che contengono alcune chiamate alle librerie e tra queste esistono i metodi "assertEquals()" che verificano che 2 oggetti (quello atteso e quello di cui si dispone) sono uguali (da cui poi tuttte le derivazioni come il confronto tra booleani, stringhe ecc.).</p>
<p>Nonostante siamo alla versione 4.x la serie precedente, 3.x, viene mantenuta questo perchè le classi che contengono i metodi devono essere opportunamente scritte, in particolare con la 3.x ad esempio i nomi dei metodi devono avere una certa struttura (testXXX, cioè devono iniziare per test) mentre la 4.x permette di avere una certa elasticità usando pero' le annotazioni come javadoc. Eclipse 3.4 annovera tra le sue librerie sia Junit 3 (3.8.2) e Junit 4 (4.3.1) e permette di creare Test case usando l'una o l'altra libreria. In <a href="http://www.vogella.de/articles/JUnit/article.html" target="_blank">questo esempio</a> vedere come creare Junit Test case con la versione 4.</p>
<p>Un'ultima cosa che dovete sapere su Junit è che potete raggruppare i Test case in Test suite che eseguono più test. Inoltre quando si scrivono metodi per i test può capitare che questi condividano degli oggetti inizializzati; Junit permette di inizializzare, e poi distruggere, risorse condivise tramite i metodi setUp() e tearDown(), vi lascio poi scoprire il tutto facendovi spulciare la documentazione.</p>
<p>Ant, non solo vi permette di automatizzare il tutto con il suo <a href="http://ant.apache.org/manual/OptionalTasks/junit.html" target="_blank">Junit task</a>, ma vi crea anche, a partire dai risultati di ogni test, dei sempli report.</p>
<p>Quando create dei web services usando il plugin di Axis2, <strong>Codegen Wizard</strong>, per Eclipse probabilmente avrete notato l'opzione che genera anche i test cases che alla fine non sono altro che semplici client che dovete inizializzare dando l'end point da contattare e costruendo gli oggetti che da passare allo stub. Inoltre potete modificare il file Ant generato per generare i report che vi avevo accennato prima.</p>
<p>Junit è pero' la punta di un iceberg. Difatti si sono evolute applicazioni che si occupano solo della fase di testing come <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Jakarta_Cactus" target="_blank">Cactus</a>, <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Fitnesse" target="_blank">Fitnesse</a> (che è un wiki che fa acceptance test) , <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Selenium_(software)" target="_blank">Selenium</a> che allargano l'orizzonte anche alle applicazioni web, lo stesso <a href="http://static.springframework.org/spring/docs/2.5.x/reference/testing.html" target="_blank">Spring</a> tra l'altro contiene un modulo per il testing. Se poi parliamo di performance esiste <a href="http://jakarta.apache.org/jmeter/" target="_blank">jMeter</a> (a cui <a href="http://www.soapui.org/userguide/loadtest/comparison.html" target="_blank">SOAPUI fa concorrenza</a>).</p>
<p><strong>SoapUI</strong> è una applicazione rivolta ai web services che abbiamo già incontrato quando vi ho accennatto alla possibilità di validare i file wsdl per migliorare l'interoperabilità.</p>
<p>Una delle funzionalità carine è quella di <a href="http://www.soapui.org/userguide/functional/testcases.html" target="_blank">creare al volo una richiesta SOAP </a>automaticatimente generata a partire dal file wsdl, generando poi report e test di copertura su file wsdl.</p>
<p>Junit non è poi l'unico testing framework esistono <a href="https://secure.wikimedia.org/wikipedia/en/wiki/TestNG" target="_blank">TestNG</a> ed anche <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Nunit" target="_blank">Nunit</a> (che è il porting di Junit per .NET) e una <a href="https://secure.wikimedia.org/wikipedia/en/wiki/List_of_unit_testing_frameworks" target="_blank">miriade di applicazioni</a> che vengono usate per testare i vari linguaggi.</p>
<p>A questo punto vi auguro buona esplorazione in questo mondo che, anche per me, si sta rivelando sempre più grande e al tempo stesso affascinante (soprattutto come sviluppatore pigro che vorrebbe automatizzare tutto ciò :-) ).</p>
<p>P.S: Occorre dire che lo stesso Eclipse nel suo piccolo permette di testare on-line il servizio web. Difatti cliccando con il tasto destro del mouse sul file wsdl dovreste ritrovarvi nel menu contestuale la voce <strong>Web Services</strong> da cui la sotto voce <strong>Test with Web Services Explorer</strong> che è una interfaccia web che vi permette di compilare i campi  da mandare nella richiesta SOAP e subito sotto vedere la risposta.</p>
<p>Link interessante: <a href="http://wso2.org/library/3862" target="_blank">http://wso2.org/library/3862</a></p>
<p>Alla prossima</p>
]]></content:encoded>
</item>

</channel>
</rss>
