<?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://en.wordpress.com/tag/junit/</link>
	<description>Feed of posts on WordPress.com tagged "junit"</description>
	<pubDate>Tue, 01 Dec 2009 07:03:36 +0000</pubDate>

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

<item>
<title><![CDATA[JUnit Error | The method assertEquals(Object, Object) is ambiguous for the type TestFooBar]]></title>
<link>http://cedar715.wordpress.com/2009/11/28/junit-error-the-method-assertequalsobject-object-is-ambiguous-for-the-type-testfoobar/</link>
<pubDate>Sat, 28 Nov 2009 03:12:55 +0000</pubDate>
<dc:creator>Ced@R715</dc:creator>
<guid>http://cedar715.wordpress.com/2009/11/28/junit-error-the-method-assertequalsobject-object-is-ambiguous-for-the-type-testfoobar/</guid>
<description><![CDATA[The method assertEquals(Object, Object) is ambiguous for the type TestFooBar. This was the code that]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The method assertEquals(Object, Object) is ambiguous for the type TestFooBar.</p>
<p>This was the code that is generating this COMPILER error:</p>
<p><code>public class TestFooBar{<br />
	Map map = new HashMap();<br />
	@Before<br />
	protected void setUp() throws Exception {<br />
		map.put("r", 6.9);<br />
	}<br />
	@After<br />
	protected void tearDown() throws Exception {<br />
	}<br />
	@Test<br />
	public void testErr() {<br />
		<em>assertEquals(6.9, map.get("r"));</em><br />
	}<br />
}</code></p>
<p>The compilation error is at Line 11!!</p>
<p>With the autoboxing and unboxing features of JDK 1.5, 6.9 in the above example can be passed to a method whose parameter is of type double/Double/Object. And similarly a Double(caps-D) can be passed to a method that accepts Double/double/Object.</p>
<p>Coming to JUnit, there are two assertEquals() methods:<br />
   assertEquals(double expected, double actual)<br />
and<br />
  assertEquals(java.lang.Object expected, java.lang.Object actual) </p>
<p>So, the line <em> assertEquals(6.9, map.get(&#8220;r&#8221;));</em> can be mapped to either of the above two methods, leaving the compiler in ambiguity.</p>
<p>To clear this ambiguity, convert the parameters to most specific type.<br />
<code>assertEquals(6.9, (double)map.get("r"));</code><br />
or<br />
<code>assertEquals((Double)6.9, map.get("r"));</code></p>
<p>Happy Testing <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[OOPD - Uge 2, tirsdag]]></title>
<link>http://sorendahlgaard.wordpress.com/2009/11/20/oopd-uge-2-tirsdag/</link>
<pubDate>Fri, 20 Nov 2009 18:03:06 +0000</pubDate>
<dc:creator>sorendahlgaard</dc:creator>
<guid>http://sorendahlgaard.wordpress.com/2009/11/20/oopd-uge-2-tirsdag/</guid>
<description><![CDATA[Design by Contract Først lige et hængeparti. Jeg har endnu ikke snakket om clients og servers, hvilk]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2>Design by Contract</h2>
<p>Først lige et hængeparti. Jeg har endnu ikke snakket om clients og servers, hvilket er nødvendigt for at forstå dette indlæg til fulde. Følgende erdefinitionen i vores bog:</p>
<blockquote><p>A <strong>client</strong> queries and commands a <strong>server</strong></p></blockquote>
<p>I eksemplet fra sidste gang med spillet Nim ville vores Pile objekt f.eks. være en server, mens vore Player ville være en client.</p>
<p>Med det på plads kan vi kigge på contracts. Vi siger at en &#8220;kontrakt&#8221; er en aftale mellem en server og en klient om opdeling af ansvar (se evt. sidste indlæg om design by responsibility/ansvar)</p>
<p>Hvis vi f.eks. skal lave en rectangle class, der kunne have en constructor:</p>
<blockquote>
<pre><strong>public</strong> Rectangle (<strong>int</strong> height, <strong>int</strong> width) {
   <strong>this</strong>.height = height;
   <strong>this</strong>.width  = width;
}</pre>
</blockquote>
<p>I dette tilfælde kunne en klient angive negative værdier som input, hvilket ville give et absurd resultat (Vi vil f.eks. have et negativt areal). Spørgsmålet er nu: Hvis ansvar er det, at sørge for at siderne ikke bliver negative? Og hvem har ansvaret for at en areal funktion altid vil resultere i noget positivt?</p>
<p>Contracts! Vores kontrakter siger explicit hvem der har ansvaret for hvad. Kontrakter er en del af en klasses specifikation, og er derfor også en del af dokumentationen. Vores kontrakter er altså ikke en del af Java (eller andre sprog), hvilket betyder at vi har helt frie hænder til at specificere dem som vi vil.</p>
<p>Vi vil bruge ordene preconditions og postconditions om vores kontrakter. Preconditions er det en klient skal overholde når den kalder en funktion, og postconditions er det serveren overholder givet at preconditions er blevet overholdt. Vi bruger @require til at angive preconditions og @ensure til at angive postconditions. Vi bruger ligledes Javas indbyggede boolske syntaks alle de steder vi kan, således:</p>
<blockquote>
<pre><span style="color:#888888;">/**
 * A constructor for a simple rectangle class
 * @require width &#62; 0 &#38;&#38; height &#62; 0
 * @ensure this.width() == width
 * @ensure this.height() == height
 * @ensure this.area() &#62; 0
 */</span>
<strong>Public</strong> Rectangle(<strong>int</strong> width, <strong>int</strong> height) {
   <strong>this</strong>.width  = width;
   <strong>this</strong>.height = height;
}</pre>
</blockquote>
<p>Her angiver this.width(), this.height(), this.area() member functions der returnerer hhv. bredden, højden og arealet. På denne måde fortæller vi klienten at hvis han ikke giver lovlige værdier for width og height kan vi ikke garantere noget som helst. Dette minder lidt om implikationspil fra den matematiske logik.</p>
<p>Det er vigtigt at forstå, at dette ikke handler om at en bruger kan indtaste forkert data. Det sørger vores user interface for ikke vil ske. Hvad vi er bekymrede for er at et objekt (klienten) kalder et andet objekts (serverens) metoder med ulovligt input. Hvis dette sker er det altså pga. en programmeringsfejl!</p>
<p>Mening med denne tilgang er, at gøre det 100% klart hvor ansvaret ligger. Vi vil naturligvis sørge for at alle fejl der kan opstå ved run-time bliver opfanget, men vi vil udføre så lidt error-checking som muligt &#8211; vi vil kun tjekke for hver mulig fejl én gang. Dette betyder at vores kode bliver hurtigere og mere overskuelig, hvilket i sidste ende leder til at den er nemmere at opdatere osv. Husk hvor meget maintainability betyder når man designer et system!</p>
<p>Det kan godt være at vi kan være sikre på at vores preconditions aldrig bliver overskredet hvis vi selv skriver klient-koden, men ofte vil den kode der bestemmer input til en server bestå af komplekse beregninger, hvor der nemt kan opstå fejl. Hvis vores constructor ikke gør noget i det tilfælde har den egentlig opfyldt sit job, men det kan være at vores objekt da vil bryde sin egen class invariant (en invariant er noget om klassen der altid skal være sandt. f.eks. kunne vores rektangel invariant være, at sidelængderrne aldrig må blive negative.) Vi kan derfor blive nødt til at teste input nogle gange. Vi kunne naturligvis gøre det med et if-statement (At teste input med et if-statement og lave det om til noget acceptabelt kaldes defensive programming), men det antyder, at det er forventet opførsel at vores input er forkert. Det er det absolut ikke! Hvis en precondition bliver brudt er det jo en programmeringsfejl, og vi vil ikke lade vores program køre videre. Derfor bruger vi et assert-statement således:</p>
<blockquote>
<pre><strong>Public</strong> Rectangle(<strong>int</strong> width, <strong>int</strong> height) {
   <strong>assert</strong> width &#62; 0;
   <strong>assert</strong> height &#62; 0;
   <strong>this.</strong>width = width;
   <strong>this</strong>.height 0 height;
}</pre>
</blockquote>
<p>Det skal dog siges, at asserts ikke er slået til som standard, og skal slås til via. command line, hvilket betyder at vi ikke kan være sikre på at vores program vil blive kørt med dem. Dette betyder at nogle programmører prøver at undgå dem.</p>
<p>Det er en god øvelse at prøve at skrive preconditions og postconditions til vores klasser fra Nim-spillet.</p>
<h2>Testing og JUnit</h2>
<p>Når vi tester vores program snakker vi generelt om to typer testing.</p>
<ul>
<li><strong>Functional testing</strong>: Også kendt som black box testing. Her er den interne struktur ukendt for testeren, og målet er at se, om systemet opfylder kundens krav. Black box testing er en videnskab i sig selv, og er ikke en del af dette kursus.</li>
<li><strong>Unit testing</strong>: Unit testing handler om at teste klasser mens de bliver udviklet. I modsætning til functional testing.</li>
</ul>
<p>Mere specifikt</p>
<ul>
<li><strong>White box testing</strong>: Test cases bliver udført på baggrund af implementationen. Vi kan f.eks. skrive en test case der tester alle branches af et if-then-else statement &#8211; Dette er hvad vi gjorde i IP.</li>
<li><strong>Gray box testing</strong>: I gray box testing skriver vi test cases før implementering af programmet. Vi skriver dem udelukkende på baggrund af vores specifikationer, og sørger for at vores kode overholder disse cases.</li>
</ul>
<p>Det er umuligt at teste en funktion med al input. Det er også umuligt at vise om en funktion er rigtig &#8211; kun muligt at finde fejl. Vi er derfor nødt til at vælge smarte testcases.</p>
<p><strong>Eksempel: </strong>Lad os sige at vi har et program for en kombinationslås. Det er en simpel lås der kun har to cifre. Man skal indtaste de to rigtige cifre i rækkefølge for at låsen åbner. Hvis koden f.eks. er 23, kunne man indtaste 4, 2, 2, 3, hvorefter låsen ville åbne, da man har indtastet 23 i den rækkefølge.</p>
<p>Hvilke test-cases skal vi lave til dette objekt? Først undersøger vi hvilke states vores objekt kan befinde sig i:</p>
<ul>
<li>Låsen er åben</li>
<li>Låsen er låst</li>
<li>Første ciffer er endnu ikke blevet indtastet</li>
<li>Første ciffer har været indtastet</li>
</ul>
<p>Vi laver en test-plan:</p>
<ul>
<li>Test initial state
<ul>
<li>Vi teste om låsen er åben</li>
<li>Vi kan ikke teste om kombination er sat korrekt, da vi ikke har adgang til den!</li>
</ul>
</li>
<li>Test at den åbner rigtigt
<ul>
<li>Hvis låsen allerede er åben kan vi ikke lukke den ved at taste forkerte tal ind.</li>
<li>Hvis låsen er &#8220;reset&#8221; skal vi tjekke at den korrekt kombination åbner låsen, og at en inkorrekt kombination ikke åbner den.</li>
<li>Hvis låsen er &#8220;næsten åben&#8221; skal vi sikre os at et inkorrekt andet ciffer låser låsen, at låsen forbliver &#8220;næsten åben&#8221; hvis det første ciffer tastes ind igen, og at den åbner hvis det andet ciffer tastes ind.</li>
</ul>
</li>
<li>Test at den låser rigtigt
<ul>
<li>åben, reset og låst lås bliver låst og reset efter en &#8220;close&#8221; kommando.</li>
</ul>
</li>
</ul>
<p>Vi er interesseret i at opstille såkaldte ækvivalensgrupper som reducerer antallet af tests vi skal udføre. Det betyder, at vi kan dele vores &#8220;domæne&#8221; for testdata op i ikke sammenhængende ækvivalensgrupper, og at et sæt data fra en ækvivalensgruppe er repræsentativ for hele gruppen.</p>
<p>Eksempelvis:</p>
<ul>
<li>Kombinationer hvor først ciffer er 0 (eks. 01)</li>
<li>Kombinationer med to forskellige cifre (eks. 12)</li>
<li>Kombinationer med to ens cifre (eks. 77)</li>
<li>&#8220;Grænse-værdier&#8221; (Boundary cases) (00 og 99)</li>
</ul>
<p>Bemærk, at både 00 og 99 har 2 ens cifre, så vi kan eliminere 77 som test case. Man kunne godt tro at en test case med 0 som første ciffer ikke burde være anderledes end en med 1 som første ciffer, men det kunne være en oplagt implementation at lade låsen starte med at have et 0 indtastet. I det tilfælde skal vi sørge for at der ikke sker noget forkert.</p>
<p>Dette er en masse cases og en masse arbejde, men sådan er det normalt, og det er grunden til at man skriver testcases sammen med koden og ikke først bagefter!</p>
<h3>JUnit</h3>
<p>JUnit er et unit testing framework til Java. Det gør det nemmer at implementere unit test plans, gør det nemmere at udføre dine tests, og giver en rapportering af hvordan testningen gik bagefter.</p>
<p>Junit kan ikke lave dine tests, kan ikke fortælle dig hvad du skal gøre, og det kan ikke fixe dine bugs!</p>
<p>Strukturen af en JUnit test ser således ud:</p>
<ol>
<li><strong>Setting up </strong>- Klargør ting, og skab objekter, variabler, osv. som skal bruges i testen
<ol>
<li>@Before (før hver test funktion)</li>
<li>@BeforeClass (en gang for alle)</li>
</ol>
</li>
<li><strong>Invoking of test function </strong>- Test funktioner er hvor tests foregår. De kan evt. kalde hjælpe funktioner (dette anbefales stærkt!)
<ol>
<li>@Test</li>
</ol>
</li>
<li><strong>Tearing down </strong>- Gør rent efter test. Eksempelvis lukke brugte filer og lignende.
<ol>
<li>@After</li>
<li>@AfterClass</li>
</ol>
</li>
<li>(repeat)</li>
<li>Report result</li>
</ol>
<p>Alle tests verificeres med &#8220;assertions&#8221;. JUnit har sin egen Assert class.</p>
<p>En test klasse for vores kombinationslås kunne bl.a. indholde følgende:</p>
<blockquote>
<pre>public class CombinationLockTest {
   //Locks with the specified combinations
   private CombinationLock lock00;
   private CombinationLock lock01;
   private CombinationLock lock12;
   private CombinationLock lock99; 

   @Before
   public void setUp() {
      lock00 = new CombinationLock(00);
      lock01 = new CombinationLock(01);
      lock12 = new CombinationLock(12);
      lock99 = new CombinationLock(99);
   }

   @Test
   public void testOpenLock() {
      lock12.enter(3);
      lock12.enter(4);
      assertTrue(lock12.isOpen()); //JUnit's asserTrue
   }

   @Test
   public void testFirstDigitTwice() {
      closeLocks();
      firstDigitTwice(lock01,0,1);
      firstDigitTwice(lock12,1,2);
   }

   private void firstDigitTwice(CombinationLock lock, int first, int second) {
      lock.enter(first);
      lock.enter(first);
      assertFalse(lock.isOpen());
      lock.enter(second);
      assertTrue(lock.isOpen());
   }
}
</pre>
</blockquote>
<p>osv.</p>
<p>Det er ikke altid nødvendigt med teardown, men <strong>filer</strong> og <strong>streams</strong> <span style="text-decoration:underline;">skal</span> lukkes!</p>
<ul></ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Automated testing with JUnit]]></title>
<link>http://roshansingh.wordpress.com/2009/11/14/automated-testing-with-junit/</link>
<pubDate>Sat, 14 Nov 2009 03:22:01 +0000</pubDate>
<dc:creator>Roshan Singh</dc:creator>
<guid>http://roshansingh.wordpress.com/2009/11/14/automated-testing-with-junit/</guid>
<description><![CDATA[I have learnt some automated testing with JUnit. Junit is a java package which lets you write test s]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I have learnt some automated testing with JUnit. Junit is a java package which lets you write test suites so that you can simply run them when you program is done. It is good for software development as you can re-run the same tests again and again, and you can save some time and even avoid human generated error as missing out a particular test that happens with me over and over as I tend to forget cases.<br />
Learning JUnit is extremely easy if you have some Java knowledge. However I noted that the official website has very less tutorials available and you wont find much information on the internet also (please direct me if you happen to know any good tutorial).<br />
I grabbed &#8220;<b>Pragmatic Unit Testing</b>&#8221; by Andrew Hunt and Davis Thomas. This book is really helpful as it starts with the basics and goes through every details of JUnit. You can find a copy of the ebook if you search a little.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[en: Introduction to Test Driven Development]]></title>
<link>http://danielwildt.wordpress.com/2009/10/31/en-introduction-to-test-driven-development/</link>
<pubDate>Sat, 31 Oct 2009 18:34:24 +0000</pubDate>
<dc:creator>dwildt</dc:creator>
<guid>http://danielwildt.wordpress.com/2009/10/31/en-introduction-to-test-driven-development/</guid>
<description><![CDATA[So, I have done one presentation about Test Driven Development yesterday, touching TDD concepts and ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>So, I have done one <a href="http://www.slideshare.net/dwildt/introduction-to-test-driven-development">presentation about Test Driven Development</a> yesterday, touching <a href="http://www.agiledata.org/essays/tdd.html">TDD concepts</a> and also lots of concepts about <a href="http://dannorth.net/introducing-bdd">Behavior Driven Development (BDD)</a>. </p>
<p><!-- SlideShare error: doc is missing or has illegal characters /[^-_a-zA-Z0-9]/ --></p>
<p>There are simple concepts about the test first process. You have to write a test that fails, write code to make the test pass and then refactor your code. Keep the bar green to keep the code clean, remember this. </p>
<p>Repeat this cycle until you don’t have anything else to test for a specific feature. </p>
<p>Looking at a <a href="http://xp123.com/xplor/xp0308/index.shtml">User Story</a> and its acceptance tests, you also have to make sure you are adding business value on every test. </p>
<p>Simple right? </p>
<p>Well, you have to practice. </p>
<p>A lot. </p>
<p>Really. </p>
<p>I&#8217;m not kidding.</p>
<p>Believe me.</p>
<p>By the way, don&#8217;t leave <a href="http://martinfowler.com/bliki/TechnicalDebt.html">technical debt</a> behind. </p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/pqeJFYwnkjE&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' /><param name='allowfullscreen' value='true' /><param name='wmode' value='transparent' /><embed src='http://www.youtube.com/v/pqeJFYwnkjE&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' type='application/x-shockwave-flash' allowfullscreen='true' width='425' height='350' wmode='transparent'></embed></object></span></p>
<p>Just for information, currently I manage teams developing in Java (Web), Java (Mobile) and Delphi (Desktop/WebBroker). </p>
<p>Looking at Java Web, I&#8217;m starting to teach teams how to use <a href="http://junit.sourceforge.net/">JUnit</a> for automated unit tests, and code coverage with <a href="http://emma.sourceforge.net/">Emma</a> and <a href="http://www.eclemma.org/">EclEmma</a> (Eclipse Plug-in).</p>
<p>For Java Mobile, the solution will be based on <a href="http://j2meunit.sourceforge.net/">J2ME Unit</a> and <a href="http://www.cobertura4j2me.org/">Cobertura for Java ME</a>. </p>
<p>And Delphi, we are going with <a href="http://dunit.sourceforge.net/">DUnit</a> and <a href="http://www.cyamon.com/discover1.htm">Delphi Discover</a>, a Coverage Tool for Delphi programmers. </p>
<p>And also looking at test automation, both Delphi and Java Web apps will use <a href="http://seleniumhq.org/">Selenium</a> to help on automation of web processes. </p>
<p>Well, you can wait more articles on each of those tools and relation to Agile Development and <a href="http://xprogramming.com/xpmag/whatisxp">eXtreme Programming practices</a>.</p>
<p>So, remember: you are build tests for <strong>prevention</strong> of defects. With this you are also building tests to do regression testing. </p>
<p>Keep quality high, always.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Java-based JavaScript unit testing with Rhino]]></title>
<link>http://jugglingbits.wordpress.com/2009/10/28/java-based-javascript-unit-testing-with-rhino/</link>
<pubDate>Wed, 28 Oct 2009 21:04:36 +0000</pubDate>
<dc:creator>thomas11</dc:creator>
<guid>http://jugglingbits.wordpress.com/2009/10/28/java-based-javascript-unit-testing-with-rhino/</guid>
<description><![CDATA[At SwissProt, we test the UniProt website in several ways (though we still lack coverage, which is a]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>At <a href="http://www.isb-sib.ch/groups/geneva-/swiss-prot-i-xenarios.html">SwissProt</a>, we test the <a href="http://www.uniprot.org/">UniProt</a> website in several ways (though we still lack coverage, which is another topic). One area where testing was lacking for some time was JavaScript, which had accumulated over time to a somewhat substantial amount, about 3200 lines of code. We have <a href="http://seleniumhq.org/">Selenium</a> tests for the site as a whole, but having unit tests for individual bits of JavaScript would have been great to make development of new code easier, and increase confidence in the code.</p>
<p>Many available frameworks such as <a href="http://www.jsunit.net/">JsUnit</a> do in-browser testing. If you want to test actual UI code, that&#8217;s obviously what you need. But we have that at least partly covered with Selenium, and a problem with these tests is that they are difficult to run in an automated way, like from our ant test task. So I wanted something to easily and quickly test the UI-independent code, along with the Java code, from the command line, ant, or scripts. I also think that a standard JUnit-style test is way easier to write, but I guess that depends on what you&#8217;re used to.</p>
<p>Having read about <a href="http://www.mozilla.org/rhino/">Mozilla Rhino</a> several times, a JavaScript interpreter written in Java with good integration between the two languages, I set out to see how much work it could be to write a simple test framework. As it turned out, it wasn&#8217;t much work at all, and there&#8217;s so little code that I can show all of it in this post.</p>
<p><!--more--></p>
<p>Not only the helper classes, but also the tests themselves are written in Java, not JavaScript. The JS code to execute is passed around as Strings. That may not seem very nice, but it was very easy to implement and I don&#8217;t find it poses a problem. It&#8217;s limited in size and you don&#8217;t need to worry about syntax errors, as that code is what you&#8217;re testing in the first place.</p>
<p>Let&#8217;s look at a test first to see how it&#8217;s used, that&#8217;s the important part after all. We augmented the JS String class with a trim() method that&#8217;s supposed to behave like the one in Java. (I know that augmenting base JS classes is <a href="http://oreilly.com/catalog/9780596517748/">discouraged by Douglas Crockford</a>, so we do it very rarely.)</p>
<p>We test our String.trim() with a JUnit test extending <code>BaseJSTestCase</code>. In the test, we give our trim() method a couple of strings to trim, and simply assert that the result is the same as the one java.lang.String.trim() gives. That allows for a concise test by looping over the input strings, although you could of course just as well assertEquals() with a string literal.</p>
<pre>package core;

import java.util.Arrays;
import test.BaseJSTestCase;

public class StringTest
    extends BaseJSTestCase
{

    public StringTest()
        throws Exception
    {
        super("expasy/core/String.js");
    }

    public void testTrim()
        throws Exception
    {
        for (String str : Arrays.asList(new String[] {
                "foo",
                " foo ",
                "foo bar",
                " foo bar ",
                "!foo_23",
                " !foo_ 23 "}))
        {
            assertEquals(str.trim(),
                    eval.eval("\"" + str + "\".trim();", String.class));
        }
    }
}
</pre>
<p>As you can see, we specify the JS file containing the code to test in the constructor. This encourages a policy of having one test file per JS file, which makes navigating your tests straightforward.</p>
<p>The interaction with the JavaScript world happens via the <code>eval.eval()</code> call. Apparently there&#8217;s a JS evaluator somewhere. Unsurprisingly, it&#8217;s set in the parent:</p>
<pre>package test;

import java.io.IOException;
import junit.framework.TestCase;

public abstract class BaseJSTestCase
    extends TestCase
{
    // TODO ugly
    protected static final String SCRIPTS_PREFIX = "web/scripts/";

    private String fileUnderTest;
    protected JSEvaluator eval;

    public BaseJSTestCase(String fileUnderTest)
    {
        this.fileUnderTest = SCRIPTS_PREFIX + fileUnderTest;
    }

    protected void setUp()
        throws IOException
    {
        eval = new JSEvaluator(fileUnderTest, this.getName());
    }

    protected void tearDown()
    {
        eval.close();
        eval = null;
    }
}
</pre>
<p>Finally we&#8217;re getting to the evaluator. It&#8217;s just as simple. All the magic happens in Rhino, we only provide an interface to its Context class. We&#8217;ve seen how we pass the name of the JS file to test in our test&#8217;s constructor. Here we see how, after some plumbing, it&#8217;s read into our context via evaluateReader(). The context is stateful, so it requires re-initializing in setUp() to get a fresh one for every test. The main interface for executing tests is the <code>public  T eval(String js, Class returnType)</code> method. It evaluates the given code and casts the result to the given type T. The conversion to the correct Java type conveniently happens inside Rhino. There&#8217;s also the convenience method <code>public void eval(String js)</code> for executing test setup code whose return value is not interesting, for instance initializing some variables.</p>
<pre>package test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.Scriptable;

public class JSEvaluator
{
    private Context context = Context.enter();
    private Scriptable scope;
    private String forTest;

    JSEvaluator(String filename, String forTest)
        throws IOException
    {
        this.forTest = forTest;
        context = Context.enter();

        scope = context.initStandardObjects();
        context.evaluateReader(scope,
                new FileReader(new File(filename)), filename, 1, null);
    }

    private Object evaluate(String js)
    {
        return context.evaluateString(scope, js, forTest, 1, null);
    }

    public void eval(String js)
    {
        evaluate(js);
    }

    @SuppressWarnings("unchecked")
    public  T eval(String js, Class returnType)
        throws JSEvaluatorException
    {
        try
        {
            return (T) Context.jsToJava(evaluate(js), returnType);
        }
        catch (EvaluatorException e)
        {
            throw new JSEvaluatorException(e.getScriptStackTrace());
        }
    }

    void close()
    {
        Context.exit();
    }

    @SuppressWarnings("serial")
    public class JSEvaluatorException
        extends RuntimeException
    {
        JSEvaluatorException(String info)
        {
            super(info);
        }
    }
}
</pre>
<p>That&#8217;s it, I hope it&#8217;s helpful and shows how easy it is to use Rhino in Java code.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Unit test JPA Entities with in-memory Derby/JavaDB]]></title>
<link>http://eskatos.wordpress.com/2009/10/26/unit-test-jpa-entities-with-in-memory-derby/</link>
<pubDate>Mon, 26 Oct 2009 15:52:43 +0000</pubDate>
<dc:creator>eskatos</dc:creator>
<guid>http://eskatos.wordpress.com/2009/10/26/unit-test-jpa-entities-with-in-memory-derby/</guid>
<description><![CDATA[About two years ago I blogged about using HSQLDB to unit test JPA entities. This year, Apache releas]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><img src="http://eskatos.wordpress.com/files/2007/10/hibernate_logo.png?w=97" alt="Hibernate" title="Hibernate" width="97" height="96" class="alignright size-thumbnail wp-image-160" />About two years ago I blogged about using HSQLDB to unit test JPA entities. This year, Apache released a Derby version allowing you to use an in memory backend. As I use Derby in software I write, being able to run unit tests on the very same SGBD but in memory is a real gift.</p>
<p>For reference, here is a link to my previous post titled <a href="http://eskatos.wordpress.com/2007/10/15/unit-test-jpa-entities-with-in-memory-database/">Unit test JPA Entities with in-memory database</a>. What follows is just the very same method applied to Derby.</p>
<p><!--more--><br />
<strong>Dependencies</strong></p>
<p>Here are the dependencies I added to my project with the &#8220;test&#8221; scope :</p>
<pre>&#60;dependency&#62;
    &#60;groupId&#62;org.hibernate&#60;/groupId&#62;
    &#60;artifactId&#62;hibernate-entitymanager&#60;/artifactId&#62;
    &#60;version&#62;3.3.2.GA&#60;/version&#62;
    &#60;scope&#62;test&#60;/scope&#62;
&#60;/dependency&#62;
&#60;dependency&#62;
    &#60;groupId&#62;org.apache.derby&#60;/groupId&#62;
    &#60;artifactId&#62;derby&#60;/artifactId&#62;
    &#60;version&#62;10.5.3.0&#60;/version&#62;
    &#60;scope&#62;test&#60;/scope&#62;
&#60;/dependency&#62;</pre>
<p><strong>Persistence Unit</strong></p>
<p>Here the interesting snippet of my META-INF/persistence.xml file :</p>
<pre>&#60;persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL"&#62;
    &#60;provider&#62;org.hibernate.ejb.HibernatePersistence&#60;/provider&#62;
    &#60;class&#62;myapp.model.entities.Group&#60;/class&#62;
    &#60;class&#62;myapp.model.entities.User&#60;/class&#62;
    &#60;exclude-unlisted-classes&#62;true&#60;/exclude-unlisted-classes&#62;
    &#60;properties&#62;
        &#60;property name="hibernate.connection.url" value="jdbc:derby:memory:unit-testing-jpa"/&#62;
        &#60;property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver"/&#62;
        &#60;property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/&#62;
        &#60;property name="hibernate.hbm2ddl.auto" value="create"/&#62;
        &#60;property name="hibernate.connection.username" value=""/&#62;
        &#60;property name="hibernate.connection.password" value=""/&#62;
    &#60;/properties&#62;
&#60;/persistence-unit&#62;</pre>
<p><strong>The unit test</strong></p>
<p>Here is a simple complete test case :</p>
<pre> public class PersistenceUnitTest extends TestCase {

    private static Logger logger = Logger.getLogger(PersistenceUnitTest.class.getName());

    private EntityManagerFactory emFactory;

    private EntityManager em;

    public PersistenceUnitTest(String testName) {
        super(testName);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        try {
            logger.info("Starting in-memory database for unit tests");
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            DriverManager.getConnection("jdbc:derby:memory:unit-testing-jpa;create=true").close();
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("Exception during database startup.");
        }
        try {
            logger.info("Building JPA EntityManager for unit tests");
            emFactory = Persistence.createEntityManagerFactory("testPU");
            em = emFactory.createEntityManager();
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("Exception during JPA EntityManager instanciation.");
        }
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        logger.info("Shuting down Hibernate JPA layer.");
        if (em != null) {
            em.close();
        }
        if (emFactory != null) {
            emFactory.close();
        }
        logger.info("Stopping in-memory database.");
        try {
            DriverManager.getConnection("jdbc:derby:memory:unit-testing-jpa;shutdown=true").close();
        } catch (SQLNonTransientConnectionException ex) {
            if (ex.getErrorCode() != 45000) {
                throw ex;
            }
            // Shutdown success
        }
        VFMemoryStorageFactory.purgeDatabase(new File("unit-testing-jpa").getCanonicalPath());
    }

    public void testPersistence() {
        try {

            em.getTransaction().begin();

            User u = new User();
            u.setEmail("eskatos@yopmail.com");
            u.setFirstName("eskatos");
            u.setLastName("YOP");
            u.setOrganisation("Tagada");

            em.persist(u);
            assertTrue(em.contains(u));

            Group g = new Group();
            g1.addUser(u);

            em.persist(g);
            assertTrue(em.contains(g));

            g.removeUser(u);
            em.remove(u);
            em.merge(g);
            assertFalse(em.contains(u));

            em.getTransaction().commit();

        } catch (Exception ex) {
            em.getTransaction().rollback();
            ex.printStackTrace();
            fail("Exception during testPersistence");
        }
    }
}</pre>
<p>Et voila, now with Derby <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   !</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JUnit: Herramienta indispensable para el desarrollo Java]]></title>
<link>http://mikiorbe.wordpress.com/2009/10/23/junit-herramienta-indispensable-para-el-desarrollo-java/</link>
<pubDate>Fri, 23 Oct 2009 06:51:41 +0000</pubDate>
<dc:creator>Miguel</dc:creator>
<guid>http://mikiorbe.wordpress.com/2009/10/23/junit-herramienta-indispensable-para-el-desarrollo-java/</guid>
<description><![CDATA[Hoy voy a hablar de una herramienta que debería ser de uso común para el desarrollo. Estoy hablando ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Hoy voy a hablar de una herramienta que debería ser de uso común para el desarrollo. Estoy hablando de <a title="JUnit" href="http://www.junit.org/">JUnit</a>, la librería de pruebas unitarias más utilizado en entornos Java.</p>
<p>Las <a title="Pruebas unitarias en Wikipedia ES" href="http://es.wikipedia.org/wiki/Prueba_unitaria">pruebas unitarias</a> consisten en desarrollar código para probar una determinada funcionalidad de nuestra aplicación.</p>
<p>Vamos a ver un pequeño ejemplo. Supongamos que estamos haciendo una librería matemática que incluye una funcion para calcular el <a title="Factorial en Wikipedia ES" href="http://es.wikipedia.org/wiki/Factorial">factorial</a> de un número. Podría ser una clase parecida a la siguiente:</p>
<pre class="brush: java;">
package org.tcymu.util;

public class MathLibrary {
	public static int factorial(int n) throws IllegalArgumentException {
		int response = 1;

		if (n &#60; 0) {
			throw new IllegalArgumentException();
		}

		if (n &#62; 0) {
			response = n * factorial(n - 1);
		}

		return response;
	}
}
</pre>
<p>En esta entrada voy a utilizar las facilidades que da <a title="Eclipse" href="http://www.eclipse.org/">Eclipse</a> gracias a su integración con JUnit. Para ello en la vista <em>package</em> sobre la clase que queremos probar hacemos botón dereco -&#62; &#8220;New&#8221; -&#62; &#8220;JUnit Test Case&#8221;.</p>
<p style="text-align:center;"><a href="http://mikiorbe.wordpress.com/files/2009/10/junit_1_320x220.png"><img class="size-full wp-image-592 aligncenter" title="junit_1_320x220" src="http://mikiorbe.wordpress.com/files/2009/10/junit_1_320x220.png" alt="Nuevo Test JUnit" width="320" height="220" /></a></p>
<p>Nos aparece la siguiente ventana en la que seleccionamos &#8220;New JUnit 4 test&#8221; (tened en cuenta que JUnit 4 necesita Java 1.5 o superior).</p>
<p><a href="http://mikiorbe.wordpress.com/files/2009/10/junit_2_320x360.png"><img class="aligncenter size-full wp-image-595" title="junit_2_320x360" src="http://mikiorbe.wordpress.com/files/2009/10/junit_2_320x360.png" alt="junit_2_320x360" width="320" height="360" /></a></p>
<p>Podemos ver que nos propone un nombre para la clase de pruebas, así como un paquete y una carpeta de fuentes (por defecto propone el mismo paquete que las fuentes, aunque podríamos elegir otro). También podemos seleccionar que nos cree los siguientes métodos de apoyo para preparar el entorno de los test o liberar recursos:</p>
<p>- Métodos <code>setUp</code> y <code>tearDown</code>. Los ejecuta antes de llamar a cada método de prueba en esa clase. La secuencia sería <code>setUp</code>, <code>metodo1Test</code>, <code>tearDown</code>, <code>setUp</code>, <code>metodo2Test</code>, <code>tearDown</code>.</p>
<p>- Métodos <code>setUpBeforeClass</code> y <code>tearDownAfterClass</code>. Estos métodos se ejecutan antes y después de todos los métodos de la clase. La secuencia sería <code>setUpBeforeClass</code>, <code>metodo1Test</code>, <code>metodo2Test</code>, <code>tearDownAfterClass</code>.</p>
<p>A continuación nos pide los métodos que queremos probar. En este ejemplo seleccionamos el método que queremos probar (<code>factorial</code>) y ninguno de los métodos de apoyo (en nuestro sencillo ejemplo no necesitamos crear ni liberar nada).</p>
<p><a href="http://mikiorbe.wordpress.com/files/2009/10/junit_3_320x360.png"><img class="aligncenter size-full wp-image-596" title="junit_3_320x360" src="http://mikiorbe.wordpress.com/files/2009/10/junit_3_320x360.png" alt="junit_3_320x360" width="320" height="360" /></a></p>
<p>Tras finalizar y si no tenemos la librería JUnit 4 en el <em>Build Path</em> nos la añade. Y por último crea el esqueleto de la clase de prueba:</p>
<pre class="brush: java;">
package org.tcymu.util;

import static org.junit.Assert.*;

import org.junit.Test;

public class MathLibraryTest {

	@Test
	public void testFactorial() {
		fail(&#34;Not yet implemented&#34;);
	}

}
</pre>
<p>Hay que destacar que lo que realmente convierte al método en un test que ejecutará JUnit es la <a title="Anotaciones Java en Wikipedia ES" href="http://es.wikipedia.org/wiki/Anotaci%C3%B3n_Java">anotación Java</a> <code>@Test</code>, al igual que lo que marcaría a los métodos de apoyo serían anotaciones como <code>@BeforeClass</code>, <code>@AfterClass</code>, <code>@Before</code> y <code>@After</code>.</p>
<p>Podemos observar que el método <code>testFactorial</code> sólo contiene la línea <code>fail("Not yet implemented");</code> , por lo que si ejecutamos el test (mediante botón derecho sobre la clase de pruebas y &#8220;Run As&#8221; -&#62; &#8220;JUnit Test&#8221; se nos abre la vista de JUnit con el siguiente resultado:</p>
<p><a href="http://mikiorbe.wordpress.com/files/2009/10/junit_4.png"><img class="aligncenter size-full wp-image-597" title="junit_4" src="http://mikiorbe.wordpress.com/files/2009/10/junit_4.png" alt="junit_4" width="286" height="240" /></a></p>
<p>Por tanto es hora de implementar nuestra prueba para pasar la barra al ansiado color verde. Básicamente se hacen comprobaciones de los resultados esperados frente a los recibidos mediante la clase <code>org.junit.Assert</code> (<a title="Documentación Javadoc de JUnit" href="http://junit.org/junit/javadoc/4.5/">documentación Javadoc de JUnit</a>).</p>
<pre class="brush: java;">
package org.tcymu.util;

import static org.junit.Assert.*;

import org.junit.Assert;
import org.junit.Test;

public class MathLibraryTest {

	@Test
	public void testFactorial() {
		Assert.assertEquals(1, MathLibrary.factorial(0));
		Assert.assertTrue(1 == MathLibrary.factorial(1));
		Assert.assertEquals(24, MathLibrary.factorial(4));
		Assert.assertEquals(720, MathLibrary.factorial(6));

		boolean excepcionLanzada = false;
		try {
			MathLibrary.factorial(-1);
		} catch (IllegalArgumentException e) {
			excepcionLanzada = true;
		}
		Assert.assertTrue(excepcionLanzada);
	}

}
</pre>
<p>Vemos que utilizamos varios métodos para comprobar que se obtiene el resultado esperado. También podemos ver cómo probamos que se lanza la excepción esperada cuando el argumento no es válido (creo haber leído en algún sitio que se iba a mejorar la prueba de excepciones en próximas versiones, pero no consigo localizar la noticia).</p>
<p>Una vez que se ejecutan la prueba con éxito (la barrita verde) sabemos que el método funciona como nosotros esperamos. Ahora tras cualquier cambio en el código volveríamos a ejecutar JUnit para comprobar que no hemos roto nada. Esto nos da una gran seguridad a la hora de meter mano o <a title="Refactorización en Wikipedia ES" href="http://es.wikipedia.org/wiki/Refactorizar">refactorizar</a> métodos complejos.</p>
<p>Por último no quisiera terminar la entrada sin nombrar un par de temas relacionados con las pruebas unitarias.</p>
<p>- Una buena prueba debe ser repetible (se debe de poder lanzar cuantas veces queramos sin afectar a nada). Por ello cada vez más se automatizan las pruebas en los procesos de integración continua de forma que antes de generarse una versión de una aplicación se corren todas las pruebas para dicha aplicación.</p>
<p>- Existe un modelo de desarrollo que promueve que primero se escriban las pruebas y después el código. Es el llamado <a title="Desarrollo guiado por pruebas en Wikipedia ES" href="http://es.wikipedia.org/wiki/Desarrollo_guiado_por_pruebas">Desarrollo Guiado por Pruebas</a> o Test Driven Development (TDD).</p>
<p>Espero que os haya gustado esta pequeña introducción.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Kanban development oversimplified: a simple explanation of how Kanban adds to the ever-growing Agile toolkit]]></title>
<link>http://enggtech.wordpress.com/2009/10/22/kanban-development-oversimplified-a-simple-explanation-of-how-kanban-adds-to-the-ever-growing-agile-toolkit/</link>
<pubDate>Thu, 22 Oct 2009 16:00:06 +0000</pubDate>
<dc:creator>Visitor Blogs</dc:creator>
<guid>http://enggtech.wordpress.com/2009/10/22/kanban-development-oversimplified-a-simple-explanation-of-how-kanban-adds-to-the-ever-growing-agile-toolkit/</guid>
<description><![CDATA[Scrum and Extreme Programming currently dominate named Agile processes. Less well known, but equally]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Scrum and Extreme Programming currently dominate named Agile processes. Less well known, but equally important, Agile processes include Crystal, Dynamic Systems Development Methodology (DSDM), Feature Driven Development (FDD)</p>
<p>Today’s typical Agile process, no matter what name you call it, takes the best from the buffet of Agile practices to create a typical process where:</p>
<ol>
<li>Project needs or requirements are expressed in <strong>user stories placed in a backlog</strong>, and ideally written by Product owners (in Scrum), or customers (in XP) in collaboration with the development team. (Sometimes they magically appear.)</li>
<li><strong>Developers give high-level estimates</strong> saying how long user stories will take to complete.</li>
<li>Product owners arrange user stories into <strong>incremental releases</strong> that take typically 6 weeks to 6 months.</li>
<li>Product owners <strong>choose the next stories</strong>, highest value first, for each development time-box. The stories chosen need to “fit” into the time-box based on how quickly the team can produce software.</li>
<li>At the end of each development time-box the team should have incrementally built some of the product.  The team (proudly) <strong>demonstrates the finished product</strong> to product owners and other stakeholders.</li>
<li>The team adds up the development estimates for the user stories completed during the time-box.  This is the <strong>velocity</strong> (from XP) that’ll be used to estimate the amount that can be completed in the next time-box.</li>
<li>The team holds a <strong>retrospective</strong> to evaluate how well they’ve done and what changes could be made to the process to allow things to go better, then the next time-boxed development cycle is planned.</li>
<li>Time-boxed development continues through to release — which is a short way of saying “<strong>rinse and repeat</strong>.”</li>
</ol>
<p>There’s more common practices, such as daily standup meetings to synchronize the team, and burn-down charts to show development progress</p>
<p>Many links are laced through the essay — but here are a bunch in no particular order:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Toyota_Production_System">Toyota production system</a></li>
<li><a href="http://www.poppendieck.com/">The Poppendieks on Lean Software Development</a></li>
<li><a href="http://www.amazon.com/Software-Numbers-Low-Risk-High-Return-Development/dp/0131407287/ref=sr_1_1?ie=UTF8&#38;s=books&#38;qid=1240273543&#38;sr=1-1">Software by Numbers</a></li>
<li><a href="http://www.agilemanagement.net/Articles/Weblog/KanbaninAction.html">David Anderson on Kanban</a></li>
<li><a href="http://leansoftwareengineering.com/ksse/scrum-ban/">Corey Ladas on Scrumban</a></li>
<li><a href="http://joearnold.com/2008/03/naked-planning-kanban-simplified/">Arlo Belshee’s Naked Planning</a></li>
<li><a href="http://aaron.sanders.name/kanban/kanban-ground-rules-example-for-a-specific-team">Aaron Sanders Kanban ground rules</a></li>
<li><a href="http://www.infoq.com/articles/hiranabe-lean-agile-kanban">InfoQ article from Kenji Hiranabe on Kanban</a></li>
<li><a href="http://agileproductdesign.com/downloads/patton_kanban.ppt">My simple Powerpoint presentation on Kanban</a></li>
</ul>
<p>via <a href="http://agileproductdesign.com/blog/2009/kanban_over_simplified.html">Kanban development oversimplified: a simple explanation of how Kanban adds to the ever-growing Agile toolkit</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Test Run: Group Determination In Software Testing]]></title>
<link>http://enggtech.wordpress.com/2009/10/14/test-run-group-determination-in-software-testing/</link>
<pubDate>Wed, 14 Oct 2009 18:23:23 +0000</pubDate>
<dc:creator>Visitor Blogs</dc:creator>
<guid>http://enggtech.wordpress.com/2009/10/14/test-run-group-determination-in-software-testing/</guid>
<description><![CDATA[Pure Plurality and Majority Runoff Borda Count System Condorcet Technique and Schulze Method The Sch]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><span><a href="http://msdn.microsoft.com/en-us/magazine/dd148646.aspx#id0070007">Pure Plurality and Majority Runoff</a><br />
<a href="http://msdn.microsoft.com/en-us/magazine/dd148646.aspx#id0070019">Borda Count System</a><br />
<a href="http://msdn.microsoft.com/en-us/magazine/dd148646.aspx#id0070030">Condorcet Technique and Schulze Method</a><br />
<a href="http://msdn.microsoft.com/en-us/magazine/dd148646.aspx#id0070046">The Schulze Method in Code</a><br />
<a href="http://msdn.microsoft.com/en-us/magazine/dd148646.aspx#id0070114">More to Evaluate</a></span></p>
<p>two different multi-attribute decision techniques in the June 2005 (<a href="http://msdn.microsoft.com/magazine/cc163785">msdn.microsoft.com/magazine/cc163785</a>) and October 2006 (<a href="http://msdn.microsoft.com/magazine/cc300812">msdn.microsoft.com/magazine/cc300812</a>) installments of the Test Run column.</p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/dd148646.aspx">Test Run: Group Determination In Software Testing</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JUnit4 dan Apache Ant (1.7.1)]]></title>
<link>http://bambangpdp.wordpress.com/2009/10/10/junit4-dan-apache-ant-1-7-1/</link>
<pubDate>Sat, 10 Oct 2009 07:44:58 +0000</pubDate>
<dc:creator>bpdp</dc:creator>
<guid>http://bambangpdp.wordpress.com/2009/10/10/junit4-dan-apache-ant-1-7-1/</guid>
<description><![CDATA[Apache Ant 1.7.1 mendukung JUnit4. Berikut ini adalah sedikit tulisan untuk memanfaatkan build.xml d]]></description>
<content:encoded><![CDATA[Apache Ant 1.7.1 mendukung JUnit4. Berikut ini adalah sedikit tulisan untuk memanfaatkan build.xml d]]></content:encoded>
</item>
<item>
<title><![CDATA[More on Maven JUnit 4 testing]]></title>
<link>http://khvatov.wordpress.com/2009/10/10/more-on-maven-junit-4-testing/</link>
<pubDate>Fri, 09 Oct 2009 15:39:07 +0000</pubDate>
<dc:creator>khvatov</dc:creator>
<guid>http://khvatov.wordpress.com/2009/10/10/more-on-maven-junit-4-testing/</guid>
<description><![CDATA[In order for Surefire Maven plugin to recognize JUnit test classes their names must end in &#8230;Te]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In order for Surefire Maven plugin to recognize JUnit test classes their names must end in &#8230;Test</p>
<p>for example:</p>
<p>MyTests.java &#8211; will be ignored (even though it is annotated with @Test)</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Hadoop Unit Testing - Kinda Tough]]></title>
<link>http://coffeesgone.wordpress.com/2009/10/03/hadoop-unit-testing-kinda-tough/</link>
<pubDate>Sat, 03 Oct 2009 08:36:06 +0000</pubDate>
<dc:creator>Sam Baskinger</dc:creator>
<guid>http://coffeesgone.wordpress.com/2009/10/03/hadoop-unit-testing-kinda-tough/</guid>
<description><![CDATA[Pondering... I&#8217;ve been looking into getting some more system-wide JUnit tests in place for had]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><div class="wp-caption alignright" style="width: 234px"><img title="Painting of Pondering" src="http://www.seekyledraw.com/archives/painting-ponder.jpg" alt="Pondering..." width="224" height="162" /><p class="wp-caption-text">Pondering...</p></div>
<p>I&#8217;ve been looking into getting some more system-wide <a href="http://www.junit.org/">JUnit</a> tests in place for <a href="http://hadoop.apache.org/">hadoop</a>, but have found a few challenges. Interesting, the fine folks working on hadoop do have for themselves some unit tests, and from the code-skimming I&#8217;ve done, they do seem to spin up embedded <a href="http://hadoop.apache.org/common/docs/current/hdfs_design.html">HDFS,</a> <a href="http://hadoop.apache.org/common/docs/r0.20.1/mapred_tutorial.html">JobTracker</a>, and <a href="http://hadoop.apache.org/common/docs/r0.20.1/mapred_tutorial.html">TaskTrackers</a> (the job tracker being that bit of software that tracks the overall job you are executing while a task tracker handles the specifics of a particular map or reduce execution).</p>
<p>Back to the point at hand, I almost had the hadoo-test.jar code for the MiniMRCluster and MiniDfsCluster running perfectly except that when I submitted a job to the mini cluster I got an exception that loading the private class org.apache.hadoop.mapred.Child was not possible because the class was not found. Digging more, it seems that the class does indeed exist in the jars I&#8217;m using, specifically the hadoo-core jar, but the class loader simply will not pick it up, yet it finds other classes such as my Mapper, JobConf, etc. Very very strange. Googling hasn&#8217;t panned out and I&#8217;m not really at the point where I think I should engage<a href="http://www.cloudera.com/hadoop-mrunit"> MrUnit</a>, mostly because it ships in the context of <a href="http://www.cloudera.com/">Cloudera&#8217;s</a> hadoop code base.</p>
<p>Until I learn more about what the differences between <em>vanilla</em> hadoop and <em>cloudera</em> hadoop, I&#8217;ve resorted to building unit tests around my Mappers for the moment with only a few awkward tweaks to get it all working.</p>
<ol>
<li>Always set the system property (not a <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/conf/Configuration.html">Configuration</a> property) hadoop.log.dir. If you do not, strange failures occur, mostly when dealing with the TaskTracker but I make it a point to be on the safe side.</li>
<li>Set the system property <code>javax.xml.parsers.DocumentBuilderFactory</code> to <code>com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl</code> if you are using hadoop config files. I have no idea how this got changed in my <a href="http://maven.apache.org/">Maven</a> setup, but in my unit tests I have to set this.</li>
<li>I also set in the <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/mapred/JobConf.html">JobConf</a> the value <code>fs.default.class</code> to <code>org.apache.hadoop.fs.RawLocalFileSystem</code> and the value <code>fs.default.name</code> to <code>file:/tmp</code>. I&#8217;m not convinced both of these are absolutely necessary for me to read my input files off disk out of src/test/resources, but there it is.</li>
</ol>
<p>After all that, I can simply call the mapper&#8217;s map method is measure the results. No cluster needed.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How Much Process Is Enough?]]></title>
<link>http://farwestab.wordpress.com/2009/10/02/how-much-process-is-enough/</link>
<pubDate>Sat, 03 Oct 2009 02:43:18 +0000</pubDate>
<dc:creator>farwestab</dc:creator>
<guid>http://farwestab.wordpress.com/2009/10/02/how-much-process-is-enough/</guid>
<description><![CDATA[I have been pondering the question about how much process do you need for a very small team, perhaps]]></description>
<content:encoded><![CDATA[I have been pondering the question about how much process do you need for a very small team, perhaps]]></content:encoded>
</item>
<item>
<title><![CDATA[Tutorial: Getting started with Netbeans and JUnit plus Cobertura and Hudson (Part 3)]]></title>
<link>http://javadude.wordpress.com/2009/09/26/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura-and-hudson-part-3/</link>
<pubDate>Sat, 26 Sep 2009 09:18:47 +0000</pubDate>
<dc:creator>devdude</dc:creator>
<guid>http://javadude.wordpress.com/2009/09/26/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura-and-hudson-part-3/</guid>
<description><![CDATA[Following part 1 and 2 which covered the JUnit test class creation and the coverage evaluation by Co]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Following part 1 and 2 which covered the JUnit test class creation and the coverage evaluation by Cobertura, we will add in part 3 another dimension: Automation. So far we run the tests manually, but we want to achieve a continuous integration and test environment.</p>
<p><strong>Part 3 (Cobertura and Hudson</strong>)</p>
<p style="text-align:justify;"><strong>Preparation</strong>:</p>
<ul>
<li>Part 1 (<a href="http://javadude.wordpress.com/2009/09/25/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura/" target="_blank">link</a>)</li>
<li>Part 2 (<a href="http://javadude.wordpress.com/2009/09/25/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura-part-2/" target="_blank">link</a>)</li>
<li>Download Hudson (<a href="https://hudson.dev.java.net/" target="_blank">website</a>)</li>
<li>Running Subversion with the project uploaded<br />
<!--more--></li>
</ul>
<p><strong>Tutorial:</strong></p>
<ul>
<li><strong>Download and install Hudson</strong><br />
Hudson can run standalone (easier for testing, trialing and experimenting) or as a deployed application on an application server.<br />
Once you downloaded it, just navigate with a terminal session (aka Dos-Box) and start it with &#8220;<em>java -jar hudson.war</em>&#8220;<br />
You will get something like this:</p>
<div id="attachment_734" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_013.jpeg"><img class="size-medium wp-image-734" title="SVH20090925_013" src="http://javadude.wordpress.com/files/2009/09/svh20090925_013.jpeg?w=300" alt="Hudson" width="300" height="217" /></a><p class="wp-caption-text">Hudson</p></div>
<p>I will not go into any details of how to configure Hudson, but jump straight to our project. Maybe in another tutorial I will explain the basic setup of Hudson, but it so simple and the documentation is so good, it is easy for your to do the necessary settings.</li>
<li><strong>Tweak our Netbeans Project</strong><br />
As per standard setting when creating a new Netbeans project, the libraries are not kept in the project folder, but copied for deployment only. But Hudson need to access these libraries, one approach to solve this, is to keep the library files in the project folder.</p>
<div id="attachment_733" class="wp-caption alignnone" style="width: 267px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_012.jpeg"><img class="size-medium wp-image-733" title="SVH20090925_012" src="http://javadude.wordpress.com/files/2009/09/svh20090925_012.jpeg?w=257" alt="Netbeans Project" width="257" height="300" /></a><p class="wp-caption-text">Netbeans Project (Standard Folder)</p></div>
<div id="attachment_736" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_015.jpeg"><img class="size-medium wp-image-736" title="SVH20090925_015" src="http://javadude.wordpress.com/files/2009/09/svh20090925_015.jpeg?w=300" alt="SVH20090925_015" width="300" height="216" /></a><p class="wp-caption-text">Local Libraries</p></div>
<p>Open the project in Netbeans and open the project properties (right click project name).  In the libraries section you just click Browse and Next.</p>
<div id="attachment_737" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_016.jpeg"><img class="size-medium wp-image-737" title="SVH20090925_016" src="http://javadude.wordpress.com/files/2009/09/svh20090925_016.jpeg?w=300" alt="Libraries" width="300" height="185" /></a><p class="wp-caption-text">Libraries</p></div>
<p>Once this is done the libraries are kept locally in your project folder.<br />
Now comes the interesting part, you remember the recommendation from the previous part of the tutorial saying you should modify only the build.xml file ?</p>
<div id="attachment_738" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_017.jpeg"><img class="size-medium wp-image-738" title="SVH20090925_017" src="http://javadude.wordpress.com/files/2009/09/svh20090925_017.jpeg?w=300" alt="build-impl.xml" width="300" height="123" /></a><p class="wp-caption-text">build-impl.xml</p></div>
<p>Netbeans needs to recreate its build file after our changes. So either we change it for Netbeans and select cancel (not knowing what changes need to be done) or we redo our changes or keep them finally in our own build.xml file.</li>
<li><strong>Create new Job in Hudson</strong><br />
Your Hudson is running and you can access it via http://localhost:8080 (assuming you run it as standalone on your local machine)<br />
You see a mainpage like this</p>
<div id="attachment_741" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_001.jpeg"><img class="size-medium wp-image-741" title="SVH20090926_001" src="http://javadude.wordpress.com/files/2009/09/svh20090926_001.jpeg?w=300" alt="Hudson Portal" width="300" height="154" /></a><p class="wp-caption-text">Hudson Portal</p></div>
<p><strong>Create new Hudson Job</strong> (Build a free-style software project)</p>
<div id="attachment_743" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_003.jpeg"><img class="size-medium wp-image-743" title="SVH20090926_003" src="http://javadude.wordpress.com/files/2009/09/svh20090926_003.jpeg?w=300" alt="Create new Hudson Job" width="300" height="154" /></a><p class="wp-caption-text">Create new Hudson Job</p></div>
<p><strong>Configuration</strong> of new Job in Hudson</p>
<div id="attachment_742" class="wp-caption alignnone" style="width: 299px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_004.jpeg"><img class="size-medium wp-image-742" title="SVH20090926_004" src="http://javadude.wordpress.com/files/2009/09/svh20090926_004.jpeg?w=289" alt="New Hudson Job" width="289" height="300" /></a><p class="wp-caption-text">New Hudson Job</p></div>
<p>The following parts of the configuration page are interesting for us<br />
<strong>SVN repository</strong></p>
<div id="attachment_744" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_005.jpeg"><img class="size-medium wp-image-744" title="SVH20090926_005" src="http://javadude.wordpress.com/files/2009/09/svh20090926_005.jpeg?w=300" alt="SVN" width="300" height="137" /></a><p class="wp-caption-text">SVN</p></div>
<p><strong>Invoke Ant</strong> (please note it needs to be downloaded and configured first in the main Hudson configuration)</p>
<div id="attachment_745" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_006.jpeg"><img class="size-medium wp-image-745" title="SVH20090926_006" src="http://javadude.wordpress.com/files/2009/09/svh20090926_006.jpeg?w=300" alt="Invoke Ant" width="300" height="72" /></a><p class="wp-caption-text">Invoke Ant</p></div>
<p><strong>Trigger JUnit Report Creation</strong> (default path is usually <em>**/build/test/results/*.xml</em>)</p>
<div id="attachment_746" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_007.jpeg"><img class="size-medium wp-image-746" title="SVH20090926_007" src="http://javadude.wordpress.com/files/2009/09/svh20090926_007.jpeg?w=300" alt="JUnit Report" width="300" height="48" /></a><p class="wp-caption-text">JUnit Report</p></div>
<p><strong>Trigger Corbertura Report</strong> (default path is <em>**/build/report/cobertura/coverage.xml</em>)</p>
<div id="attachment_747" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_008.jpeg"><img class="size-medium wp-image-747" title="SVH20090926_008" src="http://javadude.wordpress.com/files/2009/09/svh20090926_008.jpeg?w=300" alt="Trigger Cobertura Report" width="300" height="127" /></a><p class="wp-caption-text">Trigger Cobertura Report</p></div>
<p>All other configuration we dont need right now (I added the email function to drop me an email if the build is broken).</li>
<li><strong>Trigger the first Build</strong>
<div id="attachment_749" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_010.jpeg"><img class="size-medium wp-image-749" title="SVH20090926_010" src="http://javadude.wordpress.com/files/2009/09/svh20090926_010.jpeg?w=300" alt="Job Screen (no build yet)" width="300" height="220" /></a><p class="wp-caption-text">Job Screen (no build yet)</p></div>
<div id="attachment_750" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_011.jpeg"><img class="size-medium wp-image-750" title="SVH20090926_011" src="http://javadude.wordpress.com/files/2009/09/svh20090926_011.jpeg?w=300" alt="First Build" width="300" height="220" /></a><p class="wp-caption-text">First Build</p></div>
<p>If everything is running fine we should have result like this (inclusive all Ant and JUnit log output)</p>
<pre class="brush: xml;">
...
BUILD SUCCESSFUL
Total time: 10 seconds
Recording test results
Publishing Cobertura coverage report...
Publishing Cobertura coverage results...
Finished: SUCCESS
</pre>
<p>Starting with the second build we will see a graph giving us tendencies over the last builds.<br />
In our sample project we have covered 100% of the classes but only 50% of the lines.</p>
<div id="attachment_751" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_013.jpeg"><img class="size-medium wp-image-751" title="SVH20090926_013" src="http://javadude.wordpress.com/files/2009/09/svh20090926_013.jpeg?w=300" alt="kk" width="300" height="265" /></a><p class="wp-caption-text">Build Overview</p></div>
<p>Test Code 50%<br />
@Test<br />
public void testApp() {<br />
TestMe tst = new TestMe();<br />
int res = tst.doSomething(3);<br />
assertEquals(&#8220;Correct value&#8221;, 0, res);</p>
<p>//res = tst.doSomething(6);<br />
//assertEquals(&#8220;Correct value&#8221;, 2, res);</p>
<p>//res = tst.doSomething(11);<br />
//assertEquals(&#8220;Correct value&#8221;, -1, res);<br />
}</p>
<p>Lets re-insert the full test code and we get this after our next build:</p>
<p><div id="attachment_753" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090926_014.jpeg"><img class="size-medium wp-image-753" title="SVH20090926_014" src="http://javadude.wordpress.com/files/2009/09/svh20090926_014.jpeg?w=300" alt="b" width="300" height="265" /></a><p class="wp-caption-text">Build Overview</p></div></li>
</ul>
<p><strong>Where to go from here:</strong></p>
<ul>
<li>Explore all the features of Hudson, eg. Javadoc feature, trigger other builds and use fingerprints.</li>
<li>Make Hudson production ready by deploying it on an application server such as Glassfish and securing it with logins,..</li>
</ul>
<p><strong>What else could I plug-in or do:</strong></p>
<ul>
<li>There is a huge number of plugins available that help you to integrate with all kind of tools and frameworks.</li>
<li>You can try the Netbeans Hudson feature (version 6.7 and higher)</li>
<li>You could try using the Firefox plugin to constantly see the build status.</li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Tutorial: Getting started with Netbeans and JUnit plus Cobertura (Part 2)]]></title>
<link>http://javadude.wordpress.com/2009/09/25/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura-part-2/</link>
<pubDate>Fri, 25 Sep 2009 04:33:05 +0000</pubDate>
<dc:creator>devdude</dc:creator>
<guid>http://javadude.wordpress.com/2009/09/25/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura-part-2/</guid>
<description><![CDATA[Following part 1 which covered the class and JUnit class creation and ended in a suspected successfu]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Following part 1 which covered the class and JUnit class creation and ended in a suspected successful test.</p>
<p><strong>Part 1 (covering Cobertura setup and execution</strong>)</p>
<p style="text-align:justify;"><strong>Preparation</strong>:</p>
<ul>
<li>Part 1 (<a href="http://javadude.wordpress.com/2009/09/25/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura/" target="_blank">link</a>)</li>
<li>Download Cobertura (<a href="http://cobertura.sourceforge.net/index.html" target="_blank">website</a>)<br />
<!--more--></li>
</ul>
<p><strong>Tutorial</strong>:</p>
<ul>
<li> <strong>Extract the Cobertura file </strong>(named cobertura-1.9.3-bin.zip, 1.9.3 is the actual version at the time of creation of this tutorial)<br />
You will find 4 library files (jars) that you need to copy somewhere. I copied them into my <em>ANT folder</em> under <em>Netbeans</em> for this tutorial, but I would recommend to copy the files into the lib folder of your project.</p>
<div id="attachment_711" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_001.jpeg"><img class="size-medium wp-image-711" title="SVH20090925_001" src="http://javadude.wordpress.com/files/2009/09/svh20090925_001.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="141" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<div id="attachment_712" class="wp-caption alignnone" style="width: 294px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_002.jpeg"><img class="size-medium wp-image-712" title="SVH20090925_002" src="http://javadude.wordpress.com/files/2009/09/svh20090925_002.jpeg?w=284" alt="Cobertura Tutorial" width="284" height="300" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div></li>
<li><strong>Add the libraries to our project</strong><br />
<em>Project Properties&#124;Libraries&#124;Run Test folder</em><br />
As I remarked before, here I point to a relative path outside my project folder which is not good practice.</p>
<p><div id="attachment_702" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_009.jpeg"><img class="size-medium wp-image-702" title="SVH20090924_009" src="http://javadude.wordpress.com/files/2009/09/svh20090924_009.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="216" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div></li>
<li><strong>Modify the Netbeans project properties file</strong><br />
There is currently no Cobertura plugin available for Netbeans (at least I am not aware of one, except one on project kenai server, but it&#8217;s not implemented yet)<br />
Open the file explorer view of our project and opent he file project.properties (which is created by Netbeans and updated when we change project settings). For serious projects I recommend to always make a copy before manually changing its content.<br />
We add 3 lines for our instrumented class files.</p>
<p><div id="attachment_713" class="wp-caption alignnone" style="width: 309px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_003.jpeg"><img class="size-medium wp-image-713" title="SVH20090925_003" src="http://javadude.wordpress.com/files/2009/09/svh20090925_003.jpeg?w=299" alt="c" width="299" height="148" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<div id="attachment_703" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_010.jpeg"><img class="size-medium wp-image-703" title="SVH20090924_010" src="http://javadude.wordpress.com/files/2009/09/svh20090924_010.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="124" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<pre class="brush: xml;">
# FOR COBERTURA
build.instrumented.dir=${build.dir}/instrumented
build.report.dir=${build.dir}/report
build.report.cobertura.dir=${build.report.dir}/cobertura
</pre>
</li>
<li><strong>Modify the Ant build script </strong><br />
Ant can do a lot, Maven maybe more. I am not an Ant expert, but at least I could bend  my brain around it and figure out how it works. So far I was the lazy Netbeans user &#8220;what is ant?&#8221;<br />
I will not explain Ant (curious readers can proceed to <a href="http://ant.apache.org/" target="_blank">ant.apache.org</a>), but you should understand the concept of tasks and dependencies.<br />
Netbeans creates to build files: a <em>build.xml</em> in your project root and a <em>build-impl.xml</em> in the nbproject subfolder. You are advised to add ant tasks in the <em>build.xml</em> file, the other file is maintained by Netbeans.<br />
First we need to tell ant to create the instrumented class files (Cobertura add some stuff to each line of our byte code). The instrumented bytecode is kept separately and does not affect our production classes.<br />
open the build.xml file, it should be empty except some header (that also imports the other buildfile) and some remarks explaining how it works. Right at the end (before the &#60;/project&#62;)  we add this</p>
<pre class="brush: xml;">
&#60;property environment=&#34;env&#34;/&#62;
&#60;taskdef classpath=&#34;cobertura.jar&#34; resource=&#34;tasks.properties&#34;/&#62;
&#60;target name=&#34;-pre-compile-test&#34;&#62;
 &#60;delete dir=&#34;${build.instrumented.dir}&#34; /&#62;
 &#60;delete dir=&#34;${build.report.cobertura.dir}&#34; /&#62;
 &#60;mkdir dir=&#34;${build.instrumented.dir}&#34; /&#62;
 &#60;mkdir dir=&#34;${build.report.cobertura.dir}&#34; /&#62;
 &#60;cobertura-instrument todir=&#34;${build.instrumented.dir}&#34;&#62;
 &#60;fileset dir=&#34;${build.classes.dir}&#34;&#62;
 &#60;include name=&#34;**/*.class&#34;/&#62;
 &#60;/fileset&#62;
 &#60;/cobertura-instrument&#62;
&#60;/target&#62;
</pre>
<p>It is not a new task (there are no dependencies here) but it overrides the task with same name in the build-impl.xml file.</p>
<pre class="brush: xml;">
&#60;    &#60;target name=&#34;-post-compile-test&#34;&#62;
 &#60;!-- Empty placeholder for easier customization. --&#62;
 &#60;!-- You can override this target in the ../build.xml file. --&#62;
 &#60;/target&#62;
</pre>
<p>Every time we test the whole project this task is called and will create the instrumented class files for us.</li>
<li><strong>Modify the class path for test execution</strong><br />
This is the part which I didnt figure as fast. The cobertura result was created and always showed 0% coverage. You need to tell Netbeans/Ant to use the instrumented classes for the test not the regular ones in your build folder.</p>
<div id="attachment_717" class="wp-caption alignnone" style="width: 267px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_004.jpeg"><img class="size-full wp-image-717" title="SVH20090925_004" src="http://javadude.wordpress.com/files/2009/09/svh20090925_004.jpeg" alt="Cobertura Tutorial" width="257" height="200" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<p>Open the project.properties file again and make sure to add the line <strong>${build.instrumented.dir}:\</strong> before your regular build path.<br />
Note the entries with ${file.reference.asm-3.0.jar}:\ were added by Netbeans when we added the Cobertura libraries. You could adjust the classpath order using the project properties as well.</p>
<pre class="brush: xml;">
javac.test.classpath=\
 ${javac.classpath}:\
 ${build.instrumented.dir}:\
 ${build.classes.dir}:\
 ${libs.junit_4.classpath}
..
run.test.classpath=\
 ${javac.test.classpath}:\
 ${build.instrumented.dir}:\
 ${build.test.classes.dir}:\
 ${file.reference.asm-3.0.jar}:\
 ${file.reference.asm-tree-3.0.jar}:\
 ${file.reference.cobertura.jar}:\
 ${file.reference.jakarta-oro-2.0.8.jar}:\
 ${file.reference.log4j-1.2.9.jar}
</pre>
<p>Executing the test for our project now will use the instrumented classes and creates a coverage result files for us (cobertura.ser, NO, you cant open the file in the editor)</li>
<li><strong>Modify the build script</strong> to convert the result file in human readable websites.<br />
I do this (breaking the previous rule) in the build-impl.xml file, but it would be fairly easy to migrate this to &#8220;our&#8221; build.xml file.<br />
Look for this section</p>
<pre class="brush: xml;">
 &#60;target depends=&#34;init,compile-test,-pre-test-run,-do-test-run&#34; if=&#34;have.tests&#34; name=&#34;-post-test-run&#34;&#62;
 &#60;fail if=&#34;tests.failed&#34;&#62;Some tests failed; see details above.&#60;/fail&#62;
 &#60;/target&#62;
</pre>
<p>and ammend it:</p>
<pre class="brush: xml;">
 &#60;target depends=&#34;init,compile-test,-pre-test-run,-do-test-run&#34; if=&#34;have.tests&#34; name=&#34;-post-test-run&#34;&#62;
 &#60;fail if=&#34;tests.failed&#34;&#62;Some tests failed; see details above.&#60;/fail&#62;
 &#60;!-- You can disable the html portion if you are using the hudson plugin and rely on the xml --&#62;
 &#60;cobertura-report format=&#34;html&#34; srcdir=&#34;${src.dir}&#34; destdir=&#34;${build.report.cobertura.dir}&#34;/&#62;
 &#60;!-- Used by the hudson plug-in --&#62;
 &#60;cobertura-report format=&#34;xml&#34; srcdir=&#34;${src.dir}&#34; destdir=&#34;${build.report.cobertura.dir}&#34;/&#62;
 &#60;delete file=&#34;cobertura.ser&#34; /&#62;
 &#60;/target&#62;
</pre>
</li>
<li><strong>Execute the tests and enjoy the results</strong><br />
You trigger the test for the whole project and your output will be like this</p>
<pre class="brush: xml;">
init:
deps-jar:
compile:
Deleting directory /home/sven/NetBeansProjects/CoberturaDemo/build/instrumented
Deleting directory /home/sven/NetBeansProjects/CoberturaDemo/build/report/cobertura
Created dir: /home/sven/NetBeansProjects/CoberturaDemo/build/instrumented
Created dir: /home/sven/NetBeansProjects/CoberturaDemo/build/report/cobertura
Cobertura 1.9.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura 1.9.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Instrumenting 1 file to /home/sven/NetBeansProjects/CoberturaDemo/build/instrumented
Instrumenting 1 file to /home/sven/NetBeansProjects/CoberturaDemo/build/instrumented
Cobertura: Saved information on 1 classes.
Cobertura: Saved information on 1 classes.
Instrument time: 77ms
Instrument time: 77ms
compile-test:
Testsuite: demo.TestMeTest
Smaller than 5
Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.099 sec

------------- Standard Output ---------------
Smaller than 5
------------- ---------------- ---------------
Cobertura: Loaded information on 1 classes.
Cobertura: Saved information on 1 classes.
test-report:
Cobertura 1.9.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura 1.9.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura: Loaded information on 1 classes.
Cobertura: Loaded information on 1 classes.
Report time: 251ms
Report time: 251ms
Cobertura 1.9.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura 1.9.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura: Loaded information on 1 classes.
Cobertura: Loaded information on 1 classes.
Report time: 107ms
Report time: 107ms
Deleting: /home/sven/NetBeansProjects/CoberturaDemo/cobertura.ser
test:
BUILD SUCCESSFUL (total time: 3 seconds)
</pre>
<p>You still will end up seeing the JUnit test result pane with &#8220;test passed&#8221;, but lets go to the report folder in our project and open the index.html file (Ignore the coverage.xml file because it is used by theHudson plugin that we will discuss in part 3)</p>
<div id="attachment_719" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_005.jpeg"><img class="size-medium wp-image-719" title="SVH20090925_005" src="http://javadude.wordpress.com/files/2009/09/svh20090925_005.jpeg?w=300" alt="Coberture Tutorial" width="300" height="238" /></a><p class="wp-caption-text">Coberture Tutorial</p></div>
<p>Ops, there is still something in <span style="color:#ff0000;"><strong>red</strong></span> !</p>
<div id="attachment_720" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_007.jpeg"><img class="size-medium wp-image-720" title="SVH20090925_007" src="http://javadude.wordpress.com/files/2009/09/svh20090925_007.jpeg?w=300" alt="Corbertura Tutorial" width="300" height="144" /></a><p class="wp-caption-text">Corbertura Tutorial</p></div>
<p>Cobertura tells us exactly which part of our method was never touched by our tests !</p>
<div id="attachment_721" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_008.jpeg"><img class="size-medium wp-image-721" title="SVH20090925_008" src="http://javadude.wordpress.com/files/2009/09/svh20090925_008.jpeg?w=300" alt="Corbertura Tutorial" width="300" height="164" /></a><p class="wp-caption-text">Corbertura Tutorial</p></div></li>
<li>Increase the code coverage&#124;<br />
Lets go back to our project and add test cases</p>
<pre class="brush: java;">
..
 @Test
 public void testApp() {
 TestMe tst = new TestMe();
 int res = tst.doSomething(3);
 assertEquals(&#34;Correct value&#34;, 0, res);

 res = tst.doSomething(6);
 assertEquals(&#34;Correct value&#34;, 2, res);

 res = tst.doSomething(11);
 assertEquals(&#34;Correct value&#34;, -1, res);
 }
..
</pre>
<p>and test again</p>
<p><div id="attachment_722" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_010.jpeg"><img class="size-medium wp-image-722" title="SVH20090925_010" src="http://javadude.wordpress.com/files/2009/09/svh20090925_010.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="164" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<p>Voila ! All lines and branches are covered. 100% (Find my remark later)&#8230;<span style="color:#339966;"><strong>GREEN</strong></span> all over.</p>
<p><div id="attachment_723" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090925_011.jpeg"><img class="size-medium wp-image-723" title="SVH20090925_011" src="http://javadude.wordpress.com/files/2009/09/svh20090925_011.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="164" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div></li>
</ul>
<p><strong>Resume:</strong><br />
I love this tool. Thanks for creating it. I cant add quality to the source (it is open source) but at least I could create this tutorial for more folks to get started. Use Corbertura !<br />
I will try Corbertura with Hudson in the next part and also try it on web applications.<br />
<strong><br />
2 more remark</strong>:<br />
Dont let fool yourself in the assumptions that covering all lines in your codebase really reflects a complete test, you still need to test the business logic of your application against various use cases !<br />
In reality 100% coder coverage is not realistic. The complexity explodes with combination of for/while loops combined with if statements, and also platform dependendant or very exceptional parts might not be possible to be covered. But try your best <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
<strong>References:</strong><br />
I could not get the tutorial running without using this pre-existing fragments/snippets/ideas and websites</p>
<ul>
<li>http://cobertura.sourceforge.net</li>
<li>http://ant.apache.org/</li>
<li>http://wiki.netbeans.org/CoberturaAnt</li>
<li>http://www.devdaily.com/blog/post/java/sample-cobertura-ant-build-script/</li>
<li>http://www.ibm.com/developerworks/java/library/j-cobertura/</li>
<li>http://weblogs.java.net/blog/fabriziogiudici/archive/2007/02/automating_test.html</li>
<li>http://cobertura.sourceforge.net/mavenCobertura.html</li>
<li>http://kenai.com/projects/nbcobertura</li>
</ul>
<p><strong>Update (2009-09-25):</strong><br />
There is a problem with the path of Cobertura. The above tutorial only works because the 4 jar files are in the ant folder, which is in the path !  I realized this after testing the project in a different environment.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Tutorial: Getting started with Netbeans and JUnit plus Cobertura (Part 1)]]></title>
<link>http://javadude.wordpress.com/2009/09/25/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura/</link>
<pubDate>Fri, 25 Sep 2009 03:06:10 +0000</pubDate>
<dc:creator>devdude</dc:creator>
<guid>http://javadude.wordpress.com/2009/09/25/tutorial-getting-started-with-netbeans-and-junit-plus-cobertura/</guid>
<description><![CDATA[I believe strongly in testing. I saw companies and products without any automatic test frameworks an]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;">I believe strongly in testing. I saw companies and products without any automatic test frameworks and the slightest change to the codebase (often in the urgent &#8216;we-need-to-fix-it-now-and-give-to-the-customer-in-1hr&#8217; mode) made parts of the product or modules prone to crashes because no one could test the changes against the complete application. In my current endevour to create a new product we embrace testing, though we dont practice <strong>TDD</strong> (test-driven-development), but at least we maximize the amount of automatic testing with tools/frameworks like Netbeans, Hudson, Cobertura and others. If you dont practice TDD, how can you judge how much of your codebase is really tested, even you assume all you business testcases are covered ?</p>
<p>The other day<strong> Code Coverage</strong> crossed my way (Thanks Chris!). Eager to find out how to &#8220;do it&#8221; or to &#8220;use it&#8221; I found a few tools suitable for the Netbeans environment. It actually drilled down to only one tool: <strong>Cobertura</strong>. It fits exactly into our landscape using <strong>Netbeans</strong> and <strong>Hudson</strong> and it is opensource.<br />
To get started with Cobertura you should be familiar (a bit) with Netbeans, JUnit and Ant. The Cobertura website offers sufficient reference for all functions and introduction to get you started. But what I missed is a tutorial the start from the scratch using Netbeans and Cobertura. I found 3 references (I will add them at the end,) which are not complete or just not working for me), so let me share the most basic getting-started steps with you.<br />
Please note: This is how I get started, it might not be complete, foolproof or even correct in all details. Please feel free to comment, correct or give other feedback !</p>
<p style="text-align:justify;"><!--more--><strong>Part 1 (covering project creation and JUnit test</strong>)</p>
<p style="text-align:justify;"><strong>Preparation</strong>:</p>
<ul>
<li>You have basic knowledge of Java and Netbeans.</li>
<li>Netbeans 6.5.1 (I guess older or newer versions work also)</li>
</ul>
<p><strong>Tutorial</strong>:</p>
<ul>
<li><strong>Create a new Java Project</strong> using the new project wizard of Netbeans<br />
Call it <em>CoberturaDemo</em>. Deselect <em>create Main class</em>.</p>
<div id="attachment_692" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_001.jpeg"><img class="size-medium wp-image-692" title="SVH20090924_001" src="http://javadude.wordpress.com/files/2009/09/svh20090924_001.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="202" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<div id="attachment_693" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_002.jpeg"><img class="size-medium wp-image-693" title="SVH20090924_002" src="http://javadude.wordpress.com/files/2009/09/svh20090924_002.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="202" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div></li>
<li><strong>Create a new class</strong><br />
Name it <em>TestMe</em> in the package <em>demo</em></p>
<p><div id="attachment_694" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_003.jpeg"><img class="size-medium wp-image-694" title="SVH20090924_003" src="http://javadude.wordpress.com/files/2009/09/svh20090924_003.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="202" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div></li>
<li><strong>Add some basic functionality</strong> that we can test later.<br />
It is only a function that checks an int value if smaller than 5 or even in 2 if {} statements and returns 0 or 2. Useless function but we have something to &#8220;code-cover&#8221; !</p>
<p><div id="attachment_695" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_004.jpeg"><img class="size-medium wp-image-695" title="SVH20090924_004" src="http://javadude.wordpress.com/files/2009/09/svh20090924_004.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="209" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<pre class="brush: java;">
package demo;

public class TestMe {

 public int doSomething(int i) {
 if (i &#60; 5) {
 System.out.println(&#34;Smaller than 5&#34;);
 return 0;
 }

 if (i % 2 == 0) {
 System.out.println(&#34;Even number&#34;);
 return 2;
 }

 return -1;
 }
}
</pre>
</li>
<li><strong>Add JUnit Test Skeleton for our class</strong><br />
By right-click the <em>TestMe.java</em> file in the demo package. Tools &#124; Create JUnit test.<br />
For this tutorial we leave the defaults since we are not discussing them.<br />
Netbeans will create a test skeleton file for you (TestMeTest.java)..<br />
Comment: TestMe.java was not a good name choice. All Junit Test files are called {yourClassName}Test.java.</p>
<div id="attachment_696" class="wp-caption alignnone" style="width: 292px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_005.jpeg"><img class="size-medium wp-image-696" title="SVH20090924_005" src="http://javadude.wordpress.com/files/2009/09/svh20090924_005.jpeg?w=282" alt="Cobertura Tutorial" width="282" height="300" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<div id="attachment_697" class="wp-caption alignnone" style="width: 251px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_006.jpeg"><img class="size-medium wp-image-697" title="SVH20090924_006" src="http://javadude.wordpress.com/files/2009/09/svh20090924_006.jpeg?w=241" alt="Cobertura Tutorial" width="241" height="300" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div></li>
<li><strong>Create a real JUnit test</strong><br />
The skeleton does NOTHING for us, so we need to add a test. You believe Netbeans creates testcases for you ?<br />
We create a simple test, only 1 for now, that throws a value at the method and checks for the expected value.</p>
<p><div id="attachment_700" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_007.jpeg"><img class="size-medium wp-image-700" title="SVH20090924_007" src="http://javadude.wordpress.com/files/2009/09/svh20090924_007.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="285" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<pre class="brush: java;">
package demo;

import org.junit.Test;
import static org.junit.Assert.*;

public class TestMeTest {

 public TestMeTest() {
 }

 @Test
 public void testApp() {
 TestMe tst = new TestMe();
 int res = tst.doSomething(3);
 assertEquals(&#34;Correct value&#34;, 0, res);
 }
}
</pre>
</li>
<li><strong>Execute JUnit test</strong><br />
We are already at out first testing stage ! Note that java class cannot be run, but the JUnit test.<br />
Right click on the project (project explorer) and select Test.<br />
You should get something like this:</p>
<div id="attachment_701" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.wordpress.com/files/2009/09/svh20090924_008.jpeg"><img class="size-medium wp-image-701" title="SVH20090924_008" src="http://javadude.wordpress.com/files/2009/09/svh20090924_008.jpeg?w=300" alt="Cobertura Tutorial" width="300" height="69" /></a><p class="wp-caption-text">Cobertura Tutorial</p></div>
<p>You can experiment, aka break it, by changing the expected value to 99 and execute test again.</li>
</ul>
<p style="text-align:justify;"><strong>Resume Part 1:</strong><br />
We crceate a Java class and a JUnit test class for it. We executed the test and saw &#8220;test passed&#8221;. We could belive &#8220;<em>my class is tested ! lets move on..</em>&#8220;.<br />
<strong>NO</strong> ! Half the code is <strong>NOT</strong> tested and JUnit wont tell us either ! Of course it is obvious for this most simple sample, but just think about your projects that are usually a bit more complex. Would you &#8220;see&#8221; it, if not everything is covered ? Certainly NOT. So we need a tool to tell us.</p>
<p><strong>Part 2 </strong>will introduce Cobertura as our new magic wizard to our demo project.<br />
<strong>Part 3</strong> will cover Hudson and the Cobertura plugin for Hudson.</p>
<p>Stay tuned.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[PM with J2EE experince]]></title>
<link>http://spillerlaszlo.wordpress.com/?p=2178</link>
<pubDate>Thu, 24 Sep 2009 15:22:09 +0000</pubDate>
<dc:creator>Spiller László</dc:creator>
<guid>http://spillerlaszlo.wordpress.com/?p=2178</guid>
<description><![CDATA[Duties: Developing connected services for iGO My way GPS navigation software. Requirements: 3-4 year]]></description>
<content:encoded><![CDATA[Duties: Developing connected services for iGO My way GPS navigation software. Requirements: 3-4 year]]></content:encoded>
</item>
<item>
<title><![CDATA[Behavior Driven Development]]></title>
<link>http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/</link>
<pubDate>Thu, 24 Sep 2009 02:52:28 +0000</pubDate>
<dc:creator>Sebastian Javier Marchano</dc:creator>
<guid>http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/</guid>
<description><![CDATA[Contenido 1 Introducción 1.1 Objetivos 2 Behavior Driven Development 3 Caso de uso 3.1 Introducción ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><table id="toc" border="0" summary="Contents">
<tbody>
<tr>
<td>
<div id="toctitle">
<h2>Contenido</h2>
</div>
<ul>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Introducci.C3.B3n">1 Introducción</a>
<ul>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Objetivos">1.1 Objetivos</a></li>
</ul>
</li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Behavior_Driven_Development">2 Behavior Driven Development</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Caso_de_uso">3 Caso de uso</a>
<ul>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Introducci.C3.B3n_2">3.1 Introducción</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Requerimientos">3.2 Requerimientos</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#El_Analista_Relevando_el_comportamiento">3.3 El Analista: Relevando el comportamiento</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#La_herramienta_JBehave_en_acci.C3.B3n">3.4 La herramienta: JBehave en acción</a>
<ul>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Escenarios_C.C3.B3mo_deber.C3.ADa_comportarse_la_aplicaci.C3.B3n">3.4.1 Escenarios: Cómo debería comportarse la aplicación</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Pasos_Partes_concretas_del_test">3.4.2 Pasos: Partes concretas del test</a></li>
</ul>
</li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Interacci.C3.B3n_entre_roles">3.5 Interacción entre roles</a></li>
</ul>
</li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Conclusi.C3.B3n">4 Conclusión</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Enlaces">5 Enlaces</a>
<ul>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Software_Java">5.1 Software Java</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Software_.Net">5.2 Software .Net</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Documentaci.C3.B3n">5.3 Documentación</a></li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Otros_ejemplos_de_utilizaci.C3.B3n">5.4 Ejemplos de utilización</a></li>
</ul>
</li>
<li><a href="http://sebasjm.wordpress.com/2009/09/23/behavior-driven-development/#Bibliograf.C3.ADa_adicional">Bibliografía adicional</a></li>
</ul>
</td>
</tr>
</tbody>
</table>
<p> </p>
<div id="bodyContent"><a name="Introducci.C3.B3n"></a>            </p>
<h2>Introducción</h2>
<p>Este artículo intenta acercar al lector a la práctica de desarrollo orientado a la calidad utilizando la técnica de BDD, a partir de la descripción conceptual de su utilización, beneficios, casos de uso y un ejemplo.</p>
<p><a name="Objetivos"></a></p>
<h3>Objetivos</h3>
<p>Brindar la información y los beneficios sobre esta técnica para que el lector tenga la facultad de evaluar y decidir si dicha práctica es conveniente para el proyecto en el que está trabajando.   </p>
<p><!--more Seguir leyendo--></p>
<p><a name="Behavior_Driven_Development"></a></p>
<h2>Behavior Driven Development</h2>
<p>Behavior Driven Development (también conocido como BDD) es una técnica de desarrollo ágil que fomenta la colaboración entre los desarrolladores, las personas encargadas de asegurar la calidad (testers) y los analistas en un proyecto de construcción de software. El concepto es una evolución de Test Driven Development (también denominado TDD) y Extreme Programming (XP), cuyo objetivo es  tener un mejor control de la calidad del software que está siendo producido.</p>
<p>La idea principal de BDD es enfocar el esfuerzo en describir cómo se debería comportar la aplicación (o parte de ella), plasmar esto en un sistema de análisis automático con la ayuda de herramientas y luego desarrollar, a partir de la necesidad de cumplir con el comportamiento esperado. Si el análisis ha sido lo suficientemente especifico, el desarrollo estará completo y funcionando tal como se espera cuando las métricas de las herramientas utilizadas demuestren que todos los escenarios de evaluación de comportamiento han sido finalizados con éxito.</p>
<p>Es sabido que hacer un análisis exacto es muy difícil (si no imposible) por lo cual es necesario que exista una buena comunicación entre el analista, el tester y el desarrollador para así lograr tener una corrección continua, especialmente cuando el cliente no sabe bien lo que precisa, como sucede en la mayoría de los casos.</p>
<p>A continuación se describen los tres roles principales mencionados anteriormente. Puede suceder que éstos estén fundidos en 1, 3 o X (equis) cantidad de personas, pero no necesariamente:</p>
<ul>
<li>Analistas
<ul>
<li>encargados de reelevar el comportamiento de la aplicación que satisface al cliente.</li>
</ul>
</li>
<li>Testers
<ul>
<li>son quienes llevan el relevamiento del analista a un conjunto de reglas que aplicadas al software en cuestión generan métricas para indicar el estado de avance del proyecto.</li>
</ul>
</li>
<li>Desarrolladores
<ul>
<li>encargados de implementar las funcionalidades del sistemas necesarios para cumplir con el comportamiento esperado.</li>
</ul>
</li>
</ul>
<p><a name="Caso_de_uso"></a></p>
<h2>Caso de uso</h2>
<p>Para lograr una explicación mas pragmática, a modo de ejemplo se utilizará el caso modelo elegido al azar el cual consiste en un modulo de validaciones de servicios.</p>
<p><a name="Introducci.C3.B3n_2"></a></p>
<h3>Introducción</h3>
<p>El ejemplo se trata de módulo de validación de invocaciones a servicios, el cual necesita la información de un usuario y la lista de contratos a los cuales el usuario quiere activar un servicio. A partir de estos datos, el módulo debe utilizar reglas definidas por el cliente para decidir si el servicio puede ser invocado o no.</p>
<p><a name="Requerimientos"></a></p>
<h3>El Analista: Relevando el comportamiento</h3>
<p>Desde la postura del analista, luego de una reunión con el cliente, se desprende el siguiente requerimiento:</p>
<ul>
<li><em>Cuando se activa un servicio para un contrato (línea de teléfono) por el sistema es necesario que la forma de pago sea POSPAGO</em></li>
</ul>
<p>Sabiendo esto, se puede detallar el siguiente comportamiento de la aplicación en tres pasos:</p>
<pre>Dado Un contrato pospago
Cuando Intento activar el servicio
Entonces La validación termina sin errores</pre>
<p>De esta manera se está describiendo <em>un escenario</em> de comportamiento, el cual está compuesto por tres partes importantes que es preciso saber identificar:</p>
<ul>
<li><strong>Precondición:</strong> Estado del sistema necesario y suficiente producto de la abstracción del problema, en este caso es preciso un contrato pospago. Se dice que es necesario porque sin esto el sistema no puede funcionar y suficiente porque dada la abstracción, solamente con esta información el modulo debería poder resolver el problema.</li>
<li><strong>Acción:</strong> Es la funcionalidad que se está testeando, en este caso la activación de roaming</li>
<li><strong>Poscondición:</strong> Es lo más importante, porque sin ello no hay manera de generar métricas, es el estado final del sistema luego de invocar una acción.</li>
</ul>
<p><a name="La_herramienta_JBehave_en_acci.C3.B3n"></a></p>
<h3>La herramienta: JBehave en acción</h3>
<p>Para transformar el requerimiento en algo concreto se utilizará la herramienta JBehave. Ésta permite desencadenar tests unitarios mediante el uso de reglas como las que se describieron anteriormente, asociando el escenario a un caso de test y las partes a invocaciones de test concretas. En este punto se puede apreciar como al rol del tester se le asignan incumbencias de desarrollador, aunque desde una perspectiva de cliente del módulo de validaciones ya que sólo es necesario conocer su interfaz para poder usarlo, tal como el cliente de la aplicación a la aplicación misma.</p>
<p><a name="Escenarios_C.C3.B3mo_deber.C3.ADa_comportarse_la_aplicaci.C3.B3n"></a></p>
<h4>Escenarios: Cómo debería comportarse la aplicación</h4>
<p>Como JBehave está desarrollado en idioma anglosajón, para describir el escenario anterior es necesario cambiar algunas palabras por su traducción directa</p>
<pre>Given Un contrato pospago
When Intento activar el servicio
Then La validación termina sin errores</pre>
<p>y guardar esta información en un archivo con nombre &#8216;validacion_servicio&#8217;.</p>
<p>Una vez salvado el escenario, es necesario codificar el caso de test y éste debe tener el mismo nombre que el escenario pero sin &#8216;_&#8217;, entonces se genera la clase ValidacionServicio.</p>
<p>Aunque esta convención parece aleatoria, seguir un patrón de desarrollo definido a priori y cumplirlo al pie de la letra, permite a cualquier sujeto externo al desarrollo entender los casos de test solamente conociendo la herramienta y sus prácticas. Por ejemplo, esta es una posible implementación de ValidacionServicio:</p>
<pre>public class ValidacionServicio extends Scenario {

    public ValidacionServicio() {
        super( new PasosDeValidacion() );
    }
}

public class PasosDeValidacion extends Steps {

}</pre>
<p><a name="Pasos_Partes_concretas_del_test"></a></p>
<h4>Pasos: Partes concretas del test</h4>
<p>Una vez definido el caso de test, lo siguiente es definir qué acciones responden a cada comportamiento especificado por el analista, es decir, los pasos.</p>
<p>Para eso se debe saber que para cada tipo de acción en un escenario hay una anotación correspondiente:</p>
<ul>
<li>Para las precondiciones se utiliza la anotación @Given y la funcionalidad de este método es cargar información al estado del escenario.</li>
<li>Para las acciones, la anotación @When, este método está encargado de invocar la funcionalidad a testear</li>
<li>En el caso de las poscondiciones utilizamos la anotación @Then, la cual va a permitir definir un método que verifique el estado del escenario y alerte en caso de que no cumpla con lo esperado.</li>
</ul>
<p>Es importante reiterar que como el desarrollo está gobernado por la necesidad de cumplir con los test, el 99% del tiempo de vida del proyecto más de un test estará incompleto. Teniendo en cuenta esto, se desprende que por más que haya 100 escenarios escritos, la construcción automática del software (la cual también va a generar las métricas de la herramienta de BDD) no puede estar interrumpida por el incumplimiento total o parcial del escenario, para poder permitir entregas parciales. Por eso, en este punto si se corren los tests de los escenarios sin definir todo el comportamiento, las partes incompletas se marcarán como PENDIENTES y la construcción terminará por exitosa. Diferente es cuando un test está completo y falla, lo cual puede suceder haciendo testing de regresión.</p>
<p>En esta parte, el tester necesitará el conocimiento del desarrollador o la ayuda del arquitecto para poder usar el API que permitirá invocar la funcionalidad a testear, generar las precondiciones y evaluar las poscondiciones. Para dicho caso en particular, los pasos de validaciones son los siguientes:</p>
<p> </p>
<pre>    @Given("Un contrato pospago")
    public void crearGestionyContratoPrepago(){
       // ... generar contrato y asociarlo a la forma de pago POSPAGO ...
    }
   
    @When("Intento activar el servicio")
    public void validarActivacion() {
       // ... invocar la validación y obtener el estado de la operación ...
    }
 
    @Then("La validacion termina sin errores")
    public void assertTerminaSinErrores(){
        // ... asegurar o verificar que el escenario cumpla con un estado en particular ...
        ensureThat(!validacionTerminaConErrores);
    }</pre>
<p>Una vez generados los tests, las personas con el rol de desarrollador son los encargados generar la funcionalidad necesaria. Esta vez, con requerimientos tan sólidos como la aceptación de un test automático e imparcial, las tareas delegadas son menos ambiguas y mucho más fáciles de auditar.</p>
<p><a name="Interacci.C3.B3n_entre_roles"></a></p>
<h3>Interacción entre roles</h3>
<p>Al aplicar esta práctica se pueden apreciar los beneficios enseguida que el tester comienza a trabajar sobre el escenario para generar un caso de test exhaustivo:</p>
<ul>
<li>Dado Un contrato pospago
<ul>
<li>¿Cuántas formas de pago tiene un contrato?</li>
<li>¿Es necesario contar con el cliente para esta validación?</li>
</ul>
</li>
</ul>
<ul>
<li>Cuando Intento activar el servicio
<ul>
<li>¿Qué pasa cuando se intenta desactivar el servicio?</li>
</ul>
</li>
</ul>
<p>Otra vez, el rol del analista para evacuar las incógnitas:</p>
<ul>
<li><em>Las formas de pago de un contrato son POSPAGO, PREPAGO e HIBRIDO y estas solo se van a tener en cuenta para la activación.</em></li>
</ul>
<ul>
<li><em>La aplicación no puede impedir la desvinculación de un servicio de un cliente, a lo sumo se guardará un historial de desactivaciones</em></li>
</ul>
<p>Como la manera de validar el sistema es mediante una muestra ejemplar especificada en las precondiciones, es preciso asegurarse de que estas sean lo mas amplias posibles. Entonces, sabiendo que todas las formas de pagos son POSPAGO, PREPAGO e HIBRIDO se pueden generar los siguientes escenarios:</p>
<ul>
<li><strong>Escenario 1</strong></li>
</ul>
<pre>Given Un cliente cualquiera
Given Un contrato pospago
When Intento activar el servicio
Then La validacion termina sin errores

Given Un contrato prepago
When Intento activar el servicio
Then La validacion termina con errores
 
When Intento desactivar el servicio
Then La validacion termina sin errores</pre>
<ul>
<li><strong>Escenario 2</strong></li>
</ul>
<pre>Given Un cliente cualquiera
Given Un contrato hibrido
When Intento activar el servicio
Then La validacion termina con errores</pre>
<ul>
<li><strong>Escenario 3</strong></li>
</ul>
<pre>Given Un cliente cualquiera
Given Un contrato prepago
When Intento activar el servicio
Then La validacion termina con errores</pre>
<ul>
<li><strong>Escenario 4</strong></li>
</ul>
<pre>Given Un cliente cualquiera
Given Un contrato prepago
Given Un contrato hibrido
Given Un contrato pospago
When Intento desactivar el servicio
Then La validacion termina sin errores</pre>
<p>De esta manera se puede apreciar como se están reutilizando los pasos generados en los escenarios anteriores, y al utilizar la característica de secuencialidad de los escenarios se puede generar un test lo suficientemente completo describiendo cómo la aplicación se debería comportar antes de escribir la primera línea de código.</p>
<p>Hay que tener en cuenta que tener muchos tests sobre la misma funcionalidad no brindará una métrica más precisa en cuanto progreso del proyecto pero así mismo este trabajo no es vano, puesto que ayudará definir el comportamiento más extensivamente para que el desarrollador no construya un software que responda sólo a un caso en particular. No por malas intenciones, pero podemos aceptar este archivo con reglas como un elemento de documentación dado a su lenguaje tan coloquial.</p>
<p><a name="Conclusi.C3.B3n"></a></p>
<h2>Conclusión</h2>
<p>Como se pudo apreciar en el ejemplo de caso de uso, aplicar la práctica con JBehave implica un costo muy bajo de adaptación. Solamente resta llevar a la practica la costumbre de generar escenarios de prueba previos al desarrollo y auditar las métricas constantemente para usarlas como referencia de avance.</p>
<p>Un punto en contra (o a favor, dependiendo el punto de vista) es que dicha práctica es relativamente nueva y por ende las herramientas requeridas están en desarrollo y constante cambio, sin que exista aún una en particular como referente.</p>
<p> </p>
<p><a name="Enlaces"></a></p>
<h2>Enlaces</h2>
<p><a name="Software_Java"></a></p>
<h3>Software Java</h3>
<ul>
<li><a title="http://jbehave.org/" rel="nofollow" href="http://jbehave.org/">JBehave</a></li>
<li><a title="http://www.jdave.org/" rel="nofollow" href="http://www.jdave.org/">JDave</a></li>
<li><a title="http://javastubs.sourceforge.net/" rel="nofollow" href="http://javastubs.sourceforge.net/">JavaStubs</a></li>
</ul>
<p><a name="Software_.Net"></a></p>
<h3>Software .Net</h3>
<ul>
<li><a title="http://code.google.com/p/nbehave/" rel="nofollow" href="http://code.google.com/p/nbehave/">NBehave</a></li>
<li><a title="http://nspec.tigris.org/" rel="nofollow" href="http://nspec.tigris.org/">NSpec</a></li>
<li><a title="http://nspecify.sourceforge.net/" rel="nofollow" href="http://nspecify.sourceforge.net/">NSpecify</a></li>
</ul>
<p><a name="Documentaci.C3.B3n"></a></p>
<h3>Documentación</h3>
<ul>
<li><a title="http://en.wikipedia.org/wiki/Behavior_Driven_Development" rel="nofollow" href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">Behavior Driven Development</a>en Wikipedia</li>
<li><a title="http://dannorth.net/introducing-bdd" rel="nofollow" href="http://dannorth.net/introducing-bdd">dannorth.net</a></li>
<li><a title="http://behaviour-driven.org/" rel="nofollow" href="http://behaviour-driven.org/">behaviour-driven.org</a></li>
<li><a title="http://www.ibm.com/developerworks/java/library/j-cq09187/index.html" rel="nofollow" href="http://www.ibm.com/developerworks/java/library/j-cq09187/index.html">In pursuit of code quality: Adventures in behavior-driven development</a></li>
</ul>
<p><a name="Otros_ejemplos_de_utilizaci.C3.B3n"></a></p>
<h3>Ejemplos de utilización</h3>
<ul>
<li><a title="http://jbehave.org/documentation/two-minute-tutorial/" rel="nofollow" href="http://jbehave.org/documentation/two-minute-tutorial/">Usando JBehave</a></li>
<li><a title="http://www.jdave.org/examples.html" rel="nofollow" href="http://www.jdave.org/examples.html">Usando JDave</a></li>
</ul>
<p><a name="Bibliograf.C3.ADa_adicional"></a></p>
<h2>Bibliografía adicional</h2>
<p>Las obras que se mencionan a continuación, que aún no han sido publicadas, se consideran útiles para ampliar el contenido del presente artículo.</p>
<ul>
<li><a title="http://www.amazon.com/RSpec-Book-Behaviour-Development-Cucumber/dp/1934356379/ref=sr_1_3?ie=UTF8&#38;s=books&#38;qid=1253536946&#38;sr=8-3" rel="nofollow" href="http://www.amazon.com/RSpec-Book-Behaviour-Development-Cucumber/dp/1934356379/ref=sr_1_3?ie=UTF8&#38;s=books&#38;qid=1253536946&#38;sr=8-3">The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends</a></li>
<li><a title="http://www.amazon.com/Foundations-RSpec-Behavior-driven-Development-Rails/dp/1590599225/ref=sr_1_1?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-1" rel="nofollow" href="http://www.amazon.com/Foundations-RSpec-Behavior-driven-Development-Rails/dp/1590599225/ref=sr_1_1?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-1">Foundations of RSpec: Behavior-driven Development with Ruby and Rails </a></li>
<li><a title="http://www.amazon.com/Test-Driven-Acceptance-Java-Developers/dp/1932394850/ref=sr_1_2?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-2" rel="nofollow" href="http://www.amazon.com/Test-Driven-Acceptance-Java-Developers/dp/1932394850/ref=sr_1_2?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-2">Test Driven: TDD and Acceptance TDD for Java Developers</a></li>
<li><a title="http://www.amazon.com/Test-Driven-Development-Microsoft-NET-Professional/dp/0735619484/ref=sr_1_5?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-5" rel="nofollow" href="http://www.amazon.com/Test-Driven-Development-Microsoft-NET-Professional/dp/0735619484/ref=sr_1_5?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-5">Test-Driven Development in Microsoft .NET</a></li>
<li><a title="http://www.amazon.com/Test-Driven-Development-Example-Experts-Voice/dp/1590593278/ref=sr_1_10?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-10" rel="nofollow" href="http://www.amazon.com/Test-Driven-Development-Example-Experts-Voice/dp/1590593278/ref=sr_1_10?ie=UTF8&#38;s=books&#38;qid=1253537058&#38;sr=8-10">Test-Driven Development: A J2EE Example (Expert&#8217;s Voice)</a></li>
</ul>
</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Tests unitarios en el Servidor (Java)]]></title>
<link>http://jnetmatservice.wordpress.com/2009/09/23/tests-unitarios-en-el-servidor-java/</link>
<pubDate>Wed, 23 Sep 2009 12:40:04 +0000</pubDate>
<dc:creator>eilof</dc:creator>
<guid>http://jnetmatservice.wordpress.com/2009/09/23/tests-unitarios-en-el-servidor-java/</guid>
<description><![CDATA[A la hora de ir haciendo las muy útiles pruebas unitarias para ir verificando que el código funciona]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>A la hora de ir haciendo las muy útiles pruebas unitarias para ir verificando que el código funciona correctamente, existen múltiples posibilidades para tratar este tema.</p>
<p>Por un lado están las pruebas de caja negra (ejecución de tests, digamos) y por el otro, las de caja blanca (cubrir todas las líneas de código implementadas).</p>
<h3>JUnit</h3>
<p>Con esta herramienta realizamos las pruebas. Tan simple como seguir el manual de la propia página o <em><a title="Mmmm, receta de junit ricaaaaa" href="http://junit.sourceforge.net/doc/cookbook/cookbook.htm" target="_blank">cookbok</a></em>.</p>
<h3>ECLEmma</h3>
<p>Gracias al <a title="Al rico plugin!" href="http://www.eclemma.org/" target="_blank">plugin</a> para Eclipse, se consigue averiguar la cobertura de código que se realiza con los tests. De esta forma, se consiguen unas pruebas más completas.</p>
<h3>Creando el script en Ant</h3>
<p>Al añadir a Ant las líneas adecuadas para la ejecución de pruebas de manera automática, se ha optado por usar <a title="Cobertureando" href="http://cobertura.sourceforge.net/" target="_blank">Cobertura</a>. De esta manera, se automatiza el proceso de cobertura fácilmente.</p>
<p>El proceso consiste en añadir en Ant las librerías de cobertura y después, especificar varias opciones. Todo este proceso se explica adecuadamente, a mi parecer, en la propia página de <a title="Las tareas de la hormiga para Cobertura" href="http://cobertura.sourceforge.net/anttaskreference.html" target="_blank">Cobertura</a>.</p>
<p>En nuestro caso, esta parte quedaría así:</p>
<pre style="padding-left:30px;">&#60;path id="cobertura.classpath"&#62;</pre>
<pre style="padding-left:30px;"><span style="white-space:pre;"> </span> <span style="white-space:pre;"> </span>&#60;fileset dir="${cobertura.dir}"&#62;</pre>
<pre style="padding-left:30px;"><span style="white-space:pre;"> </span> <span style="white-space:pre;"> </span>&#60;include name="cobertura.jar" /&#62;</pre>
<pre style="padding-left:30px;"><span style="white-space:pre;"> </span> <span style="white-space:pre;"> </span>&#60;include name="lib/**/*.jar" /&#62;</pre>
<pre style="padding-left:30px;"><span style="white-space:pre;"> </span> <span style="white-space:pre;"> </span>&#60;/fileset&#62;</pre>
<pre style="padding-left:30px;"><span style="white-space:pre;"> </span>&#60;/path&#62;</pre>
<p>Luego entre las opciones a especificar:</p>
<pre>&#60;!-- =================================

<span style="white-space:pre;">	</span>target: instrument

 ================================= --&#62;

<span style="white-space:pre;">	</span>&#60;target name="instrument"

<span style="white-space:pre;">		</span>description="Crea las clases de instrumentación para generar la cobertura"

<span style="white-space:pre;">		</span>depends="init.instrument"&#62;

<span style="white-space:pre;">		</span>

<span style="white-space:pre;">		</span>&#60;!-- Se eliminan los ficheros de ejecuciones anteriores --&#62;

<span style="white-space:pre;">		</span>&#60;delete file="cobertura.ser" /&#62;

<span style="white-space:pre;">		</span>&#60;delete dir="${build.instrumented.dir}" /&#62;

<span style="white-space:pre;">		</span>

<span style="white-space:pre;">		</span>&#60;cobertura-instrument todir="${build.instrumented.dir}"&#62;

<span style="white-space:pre;">	</span>    <span style="white-space:pre;">	</span>&#60;fileset dir="${build.dir}/classes"&#62;

<span style="white-space:pre;">	</span>        <span style="white-space:pre;">	</span>&#60;include name="**/*.class" /&#62;

<span style="white-space:pre;">	</span>    <span style="white-space:pre;">	</span>    &#60;exclude name="**/*Test.class" /&#62;

<span style="white-space:pre;">		</span>    &#60;/fileset&#62;

<span style="white-space:pre;">		</span>&#60;/cobertura-instrument&#62;

<span style="white-space:pre;">	</span>&#60;/target&#62;

<span style="white-space:pre;">	</span>

&#60;!-- =================================

<span style="white-space:pre;">	</span>target: test

 ================================= --&#62;

<span style="white-space:pre;">	</span>&#60;target name="test" depends="init,compile,instrument" description="Ejecuta las pruebas de cobertura. Para ello es necesario

<span style="white-space:pre;">		</span>tener ejecutando el motor de MySQL y Matlab."&#62;

<span style="white-space:pre;">		</span>&#60;junit fork="yes" dir="${basedir}" failureProperty="test.failed"&#62;

<span style="white-space:pre;">	</span>    <span style="white-space:pre;">	</span>&#60;classpath location="${build.instrumented.dir}"/&#62;

<span style="white-space:pre;">	</span>    <span style="white-space:pre;">	</span>&#60;classpath location="${build.classes.dir}"/&#62;

<span style="white-space:pre;">			</span>&#60;classpath location="${build.dir}"/&#62;

<span style="white-space:pre;">			</span>&#60;classpath refid="sql.classpath" /&#62;

<span style="white-space:pre;">			</span>

<span style="white-space:pre;">			</span>&#60;formatter type="xml"/&#62;

<span style="white-space:pre;">			</span>&#60;classpath refid="cobertura.classpath" /&#62;

<span style="white-space:pre;">			</span>

<span style="white-space:pre;">			</span>&#60;formatter type="xml" /&#62;

<span style="white-space:pre;">			</span>&#60;test name="${testcase}" todir="${report.junit.dir}" if="testcase"/&#62;

<span style="white-space:pre;">		</span>

<span style="white-space:pre;">			</span>&#60;batchtest todir="${junit.xml.dir}" unless="testcase"&#62;

<span style="white-space:pre;">				</span>&#60;fileset dir="${test.dir}"&#62;

<span style="white-space:pre;">					</span>&#60;include name="**/*.java"/&#62;

<span style="white-space:pre;">				</span>&#60;/fileset&#62;

<span style="white-space:pre;">			</span>&#60;/batchtest&#62;

<span style="white-space:pre;">		</span>&#60;/junit&#62;

<span style="white-space:pre;">		</span>

<span style="white-space:pre;">		</span>&#60;junitreport todir="${junit.xml.dir}"&#62;

<span style="white-space:pre;">			</span>&#60;fileset dir="${junit.xml.dir}"&#62;

<span style="white-space:pre;">				</span>&#60;include name="TEST-*.xml"/&#62;

<span style="white-space:pre;">			</span>&#60;/fileset&#62;

<span style="white-space:pre;">			</span>&#60;report format="frames" todir="${junit.html.dir}" /&#62;

<span style="white-space:pre;">		</span>&#60;/junitreport&#62;

<span style="white-space:pre;">	</span>&#60;/target&#62;

<span style="white-space:pre;">	</span>

&#60;!-- =================================

<span style="white-space:pre;">	</span>target: coverage-check

 ================================= --&#62;

<span style="white-space:pre;">	</span>&#60;target name="coverage-check" depends="" description="Comprueba que las pruebas de cobertura están en un intervalo especificado"&#62;

<span style="white-space:pre;">			</span>&#60;cobertura-check branchrate="35" totallinerate="100" /&#62;

<span style="white-space:pre;">	</span>&#60;/target&#62;

<span style="white-space:pre;">	</span>

&#60;!-- =================================

<span style="white-space:pre;">	</span>target: coverage-report

 ================================= --&#62;

<span style="white-space:pre;">	</span>&#60;target name="coverage-report" depends="test" description="Crea un informe html con la cobertura de las pruebas"&#62;

<span style="white-space:pre;">		</span>&#60;cobertura-report destdir="${cobertura.html.dir}"&#62;

<span style="white-space:pre;">		</span>   &#60;fileset dir="${src.dir}"&#62;

<span style="white-space:pre;">		</span>       &#60;include name="**/*.java" /&#62;

<span style="white-space:pre;">		</span>       &#60;exclude name="**/*Stub.java" /&#62;

<span style="white-space:pre;">		</span>   &#60;/fileset&#62;

<span style="white-space:pre;">		</span>&#60;/cobertura-report&#62;

<span style="white-space:pre;">	</span>&#60;/target&#62;

<span style="white-space:pre;">	</span>

&#60;!-- =================================

<span style="white-space:pre;">	</span>target: coverage-report-xml

 ================================= --&#62;

<span style="white-space:pre;">	</span>&#60;target name="coverage-report-xml" depends="coverage-report" description="Crea un informe xml con la cobertura de las pruebas"&#62;

<span style="white-space:pre;">	</span>    &#60;cobertura-report format="xml" srcdir="${src.dir}" destdir="${cobertura.xml.dir}"/&#62;

<span style="white-space:pre;">	</span>&#60;/target&#62;</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[The Perfect Unit Test (for this class at least)]]></title>
<link>http://research2009.wordpress.com/2009/09/21/the-perfect-unit-test-for-this-class-at-least/</link>
<pubDate>Mon, 21 Sep 2009 17:46:38 +0000</pubDate>
<dc:creator>Jose  Asuncion</dc:creator>
<guid>http://research2009.wordpress.com/2009/09/21/the-perfect-unit-test-for-this-class-at-least/</guid>
<description><![CDATA[I enjoyed writing this test. It tells a story. public class WordPressPreviewTestCase extends TestCas]]></description>
<content:encoded><![CDATA[I enjoyed writing this test. It tells a story. public class WordPressPreviewTestCase extends TestCas]]></content:encoded>
</item>
<item>
<title><![CDATA[Unit testing guidelines]]></title>
<link>http://bogdanmocanu.wordpress.com/2009/09/19/unit-testing-guidelines/</link>
<pubDate>Sat, 19 Sep 2009 09:13:07 +0000</pubDate>
<dc:creator>Bogdan Mocanu</dc:creator>
<guid>http://bogdanmocanu.wordpress.com/2009/09/19/unit-testing-guidelines/</guid>
<description><![CDATA[While developing a product, an important part of the development process is writing unit tests. Thes]]></description>
<content:encoded><![CDATA[While developing a product, an important part of the development process is writing unit tests. Thes]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala introduction -- writing an OAuth library]]></title>
<link>http://benbiddington.wordpress.com/2009/09/18/scala-introduction-writing-an-oauth-library/</link>
<pubDate>Fri, 18 Sep 2009 12:37:37 +0000</pubDate>
<dc:creator>benbiddington</dc:creator>
<guid>http://benbiddington.wordpress.com/2009/09/18/scala-introduction-writing-an-oauth-library/</guid>
<description><![CDATA[I started out intending to write some scala examples against the twitter API, however I soon discove]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I started out intending to write some scala examples against the twitter API, however I soon discovered I needed OAuth first. Given that I use OAuth all the time at work I figured I could probably do with learning about it first-hand, while learning scala.</p>
<h2>org.junit.rules._</h2>
<p>I chose to test drive it with JUnit 4.7 and NetBeans.</p>
<p>NetBeans works almost immediately with scala, and has support for project templates etc &#8212; even scala JUnit fixtures.</p>
<p>JUnit mostly works, though rules don&#8217;t and neither do some matchers. Even though rules don&#8217;t work, I have included it anyway because <a href="http://www.cafepress.com/3riversinst.398018535" target="_blank">I have the t-shirt</a>.</p>
<p>You can <a href="http://github.com/ben-biddington/scala-oauth/" target="_blank">find the project on github</a>.</p>
<h2>Important abstractions</h2>
<ol>
<li><a href="http://github.com/ben-biddington/scala-oauth/blob/c7bdd1663e7e7774b5c2327fe29af7c7a81f662e/test/org/coriander/oauth/SignatureBaseStringTest.scala" target="_blank">SignatureBaseString</a>.
<ol>
<li>Characterized by three ampersand-separated segments: verb, uri, parameters.</li>
<li>URL Encoding must conform to <a href="http://oauth.net/core/1.0/#RFC3986" target="_blank">RFC 3986</a>, and the following characters should are consider unreserved so should not be encoded:<br />
ALPHA, DIGIT, &#8216;-&#8217;, &#8216;.&#8217;, &#8216;_&#8217;, &#8216;~&#8217;</li>
</ol>
</li>
<li><a href="http://github.com/ben-biddington/scala-oauth/blob/c7bdd1663e7e7774b5c2327fe29af7c7a81f662e/test/org/coriander/oauth/SignatureTest.scala" target="_blank">Signature</a>.
<ol>
<li><span style="background-color:#ffffff;">Signature is a <a href="http://en.wikipedia.org/wiki/HMAC" target="_blank">keyed-Hash Message Authentication Code (HMAC)</a>.</span></li>
<li><span style="background-color:#ffffff;">Consumer secret required part of HMAC secret key.</span></li>
<li>Token secret is optionally included in HMAC secret key:<br />
(consumer_secret, token_secret) =&#62; uri_encoded_consumer_secret&#38;[uri_encoded_token_secret]</li>
</ol>
</li>
<li><span style="background-color:#ffffff;"><a href="http://github.com/ben-biddington/scala-oauth/blob/c7bdd1663e7e7774b5c2327fe29af7c7a81f662e/src/org/coriander/oauth/OAuthCredential.scala" target="_blank">OAuthCredential</a>. Represents the secret key(s) used to create the HMAC signature. OAuth requires a <strong>consumer</strong> credential, and optionally a <strong>token</strong> credential, representing the end user.</span></li>
</ol>
<p>Now that these core concepts are complete, I am working on high-level policy, like classes for generating signed URLs and authorization headers.</p>
<h2>Notes</h2>
<h3>JUnit &#8212; expecting exceptions in scala</h3>
<p>Assuming JUnit 4.x, a test can expect an exception using the test annotation:</p>
<p><strong>Java</strong>:</p>
<pre style="font:normal normal normal 12px/18px Consolas, Monaco, 'Courier New', Courier, monospace;">@Test(expected=IllegalArgumentException.class)
    public void ExampleThrowsException(){
        throw new IllegalArgumentException();
    }</pre>
<p>This needs to be modified for scala:</p>
<p><strong>Scala</strong>:</p>
<pre style="font:normal normal normal 12px/18px Consolas, Monaco, 'Courier New', Courier, monospace;">@Test { val expected=classOf[IllegalArgumentException] }
    def ExampleThrowsException {
        throw new IllegalArgumentException
    }</pre>
<p>The reason for it is outlined <a href="http://www.scala-lang.org/node/106" target="_blank">here</a> in the <em>Java annotations</em> section on named parameters.</p>
<p>Here is <a href="http://www.scala-lang.org/node/106" target="_blank">the documentation for scala annotations</a>. Seealso: <a href="http://scaladocs.jcraft.com/2.7.3/" target="_blank">the documentation for scala 2.7.3</a> (includes dbc).</p>
<h3>Closures and return</h3>
<p>The return statement immediately returns from the current method, even if you&#8217;re within a closure. Omit return in this case &#8212; return is optional anyway.</p>
<h3>When to use semicolon line terminator</h3>
<p><strong><span style="background-color:#ffffff;font-weight:normal;">Never &#8212; apart from: </span></strong></p>
<ul>
<li><span style="background-color:#ffffff;">When a method returns <em>Unit</em> (equivalent to void) and you aren&#8217;t using return keyword. [TBD: Add example].</span></li>
</ul>
<h3>How to use blocks</h3>
<pre>var count = 1
times(2) { println("Printed " + count + " times")}
protected def times(count : Int)(block : =&#62; Unit) = {
<span style="background-color:#ffffff;">    1.to(count).foreach((_) =&#62; block)
<span style="font-family:Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;line-height:19px;white-space:normal;font-size:13px;">}</span></span></pre>
<p><strong><span style="background-color:#ffffff;font-weight:normal;"><strong>References</strong></span></strong></p>
<ul>
<li><span style="background-color:#ffffff;"><a href="http://github.com/ben-biddington/scala-oauth/" target="_blank">Scala oauth lib</a> (Github).</span></li>
<li><span style="background-color:#ffffff;"><a href="http://oauth.net/documentation/spec" target="_blank">OAuth specification</a>.</span></li>
<li><span style="background-color:#ffffff;"><a href="http://scaladocs.jcraft.com/2.7.3/" target="_blank">Scala 2.7.3 documentation</a>.</span></li>
<li><span style="background-color:#ffffff;"><a href="http://oauth.rubyforge.org/" target="_blank">OAuth ruby gem</a>.</span></li>
<li><span style="background-color:#ffffff;"><a href="http://term.ie/oauth/example/client.php" target="_blank">OAuth test client</a>.</span></li>
</ul>
<div id="_mcePaste" style="overflow:hidden;position:absolute;left:-10000px;top:172px;width:1px;height:1px;">
<pre>ALPHA, DIGIT, '-', '.', '_', '~'</pre>
</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JSF - Aplicação rich:editor + Facelets]]></title>
<link>http://serjaum.wordpress.com/2009/09/15/jsf-aplicacao-pratica-utilizando-richeditor/</link>
<pubDate>Tue, 15 Sep 2009 01:37:36 +0000</pubDate>
<dc:creator>serjaumfantin</dc:creator>
<guid>http://serjaum.wordpress.com/2009/09/15/jsf-aplicacao-pratica-utilizando-richeditor/</guid>
<description><![CDATA[Neste post irei demonstrar a utilização do componente rich:editor que faz parte da biblioteca de com]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><span style="color:#000000;">Neste post irei demonstrar a utilização do componente <a href="http://livedemo.exadel.com/richfaces-demo/richfaces/editor.jsf?c=editor&#38;tab=usage">rich:editor</a> que faz parte da biblioteca de componentes RichFaces.</span></p>
<p><span style="color:#000000;">O rich:editor é um componente usado para a criação de um editor em páginas. Seu uso é relativamente simples e o resultado é impressionante.</span></p>
<p><span style="color:#000000;">A aplicação consiste num cadastro de Rascunhos onde o usuário poderá cadastrar e remover seus rascunhos de uma forma prática e simples. Para gerenciar as sessões/transações do Hibernate criei um serlvet filter <a href="https://www.hibernate.org/43.html">Open Session In View</a> fazendo papel de um interceptador, que será executado a cada request e response.</span></p>
<p><span style="color:#000000;">Utilizarei <a href="http://tomcat.apache.org/">Tomcat</a>, <a href="https://www.hibernate.org/">Hibernate</a> e <a href="http://www.mysql.com/">MySQL</a> para a persistência de dados e disponilizarei o projeto para download.</span></p>
<h2>Estrutura do projeto</h2>
<p style="text-align:center;"><img class="aligncenter size-full wp-image-843" title="rich_editor" src="http://serjaum.wordpress.com/files/2009/09/rich_editor.png" alt="rich_editor" width="280" height="500" /></p>
<h2>Versões utilizadas</h2>
<ul>
<li><span style="color:#000000;">Eclipse 3.4.1</span></li>
<li><span style="color:#000000;">JDK 1.6</span></li>
<li><span style="color:#000000;">Tomcat 6.0.18</span></li>
<li><span style="color:#000000;">MyFaces 1.2.5</span></li>
<li><span style="color:#000000;">RichFaces 3.3.1</span></li>
<li><span style="color:#000000;">Hibernate Annotations 3.4.0</span></li>
<li><span style="color:#000000;">Hibernate 3.3.1</span></li>
<li><span style="color:#000000;">MySQL 5</span></li>
<li><span style="color:#000000;">MySQL Query Browser 1.2</span></li>
</ul>
<h2>Códigos</h2>
<p><strong>Rascunho.java: </strong></p>
<blockquote>
<pre>package br.com.serjaum.modelo;

@Entity
@Table(name="rascunho")
public class Rascunho implements Serializable{

 private static final long serialVersionUID = -6142163109498247473L;

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="RASCUNHO_ID")
 private Long id;

 @Column(name="titulo")
 private String titulo;

 @Temporal(TemporalType.DATE)
 @Column(name="data")
 private Date data = new Date();    

 @Lob
 @Column(name="conteudo")
 private String conteudo;

...
}</pre>
</blockquote>
<p><!--more--><strong>RascunhoMB.java: </strong></p>
<blockquote>
<pre>package br.com.serjaum.mb;

public class RascunhoMB implements Serializable {

 private static final long serialVersionUID = -7138652046367400871L;

 private Long id;

 private Rascunho rascunho = new Rascunho();

 public RascunhoMB(){
 System.out.println(" &#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62;&#62; Construtor do RASCUNHO_MB &#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;&#60;");

 if(this.rascunho == null){
 this.rascunho = new Rascunho();
 }
 }

 public String save(){
 Session session = HibernateUtil.currentSession();
 RascunhoDAO rascunhoDAO = new RascunhoDAO(session, Rascunho.class);

 rascunhoDAO.save(this.rascunho);

 this.rascunho = new Rascunho();
 return "toIndex";
 }

 public String delete(){
 Session session = HibernateUtil.currentSession();
 RascunhoDAO rascunhoDAO = new RascunhoDAO(session, Rascunho.class);

 this.rascunho = rascunhoDAO.load(this.id);
 rascunhoDAO.delete(this.rascunho);
 this.rascunho = new Rascunho(); 

 return "removeSucesso";
 }

 public String merge(){
 Session session = HibernateUtil.currentSession();
 RascunhoDAO rascunhoDAO = new RascunhoDAO(session, Rascunho.class);
 rascunhoDAO.merge(this.rascunho);
 this.rascunho = new Rascunho(); 

 return "atualizaSucesso";
 }

 public String load(){
 Session session = HibernateUtil.currentSession();
 RascunhoDAO rascunhoDAO = new RascunhoDAO(session, Rascunho.class);

 this.rascunho = rascunhoDAO.load(this.id);

 return "pesquisaSucesso";
 }

 public String pesquisaByTitulo(){
 Session session = HibernateUtil.currentSession();
 RascunhoDAO rascunhoDAO = new RascunhoDAO(session, Rascunho.class);

 this.rascunho = rascunhoDAO.pesquisaRascunhoByTitulo(this.rascunho.getTitulo());

 return "pesquisaByTituloSucesso";
 }

 public String exibeRascunho(){
 Session session = HibernateUtil.currentSession();
 RascunhoDAO rascunhoDAO = new RascunhoDAO(session, Rascunho.class);

 this.rascunho = rascunhoDAO.load(this.id);

 return "toRascunho";
 }

 public List&#60;Rascunho&#62; getRascunhos(){
 Session session = HibernateUtil.currentSession();
 RascunhoDAO rascunhoDAO = new RascunhoDAO(session, Rascunho.class);

 return rascunhoDAO.list();
 }

 public Long getId() {
 return id;
 }

 public void setId(Long id) {
 this.id = id;
 }

 public Rascunho getRascunho() {
 return rascunho;
 }

 public void setRascunho(Rascunho rascunho) {
 this.rascunho = rascunho;
 }
}</pre>
</blockquote>
<p><strong>cadastraRascunho.xhtml: </strong></p>
<blockquote>
<pre>&#60;?xml version="1.0" encoding="ISO-8859-1"?&#62;
&#60;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&#62;
&#60;html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:ui="http://java.sun.com/jsf/facelets"
 xmlns:h="http://java.sun.com/jsf/html"
 xmlns:f="http://java.sun.com/jsf/core"
 xmlns:a4j="http://richfaces.org/a4j"
 xmlns:rich="http://richfaces.org/rich"&#62;
 &#60;head&#62;
 &#60;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /&#62;
 &#60;/head&#62;

 &#60;a4j:keepAlive beanName="rascunhoMB" /&#62;

 &#60;ui:composition template="/template/template.xhtml"&#62;
 &#60;ui:define name="corpo"&#62;
 &#60;h:form&#62;
 &#60;rich:messages /&#62;

 &#60;fieldset&#62;
 &#60;legend&#62;Rascunho&#60;/legend&#62;
 &#60;h:panelGrid columns="1"&#62;
 &#60;h:outputLabel for="titulo" value="Título "/&#62;
 &#60;h:inputText id="titulo" value="#{rascunhoMB.rascunho.titulo }" required="true" requiredMessage="Preencha o Título do Rascunho" styleClass="edit" size="35" /&#62;

 &#60;h:outputLabel for="conteudo" value="Conteúdo "  /&#62;
 &#60;rich:editor id="conteudo" theme="advanced" value="#{rascunhoMB.rascunho.conteudo}" required="true" requiredMessage="Preencha o Conteúdo do Rascunho" height="300" width="700"/&#62;
 &#60;/h:panelGrid&#62;

 &#60;a4j:commandButton value="Salvar " action="#{rascunhoMB.save}" styleClass="botoes"/&#62;
 &#60;h:commandButton value="Voltar " action="toIndex" immediate="true" styleClass="botoes"/&#62;
 &#60;/fieldset&#62;
 &#60;/h:form&#62;
 &#60;/ui:define&#62;
 &#60;/ui:composition&#62;
&#60;/html&#62;</pre>
</blockquote>
<p><strong>rascunho.xhtml: </strong></p>
<blockquote>
<pre>&#60;?xml version="1.0" encoding="ISO-8859-1"?&#62;
&#60;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&#62;
&#60;html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:ui="http://java.sun.com/jsf/facelets"
 xmlns:h="http://java.sun.com/jsf/html"
 xmlns:f="http://java.sun.com/jsf/core"
 xmlns:a4j="http://richfaces.org/a4j"
 xmlns:rich="http://richfaces.org/rich"&#62;
 &#60;head&#62;
 &#60;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /&#62;
 &#60;/head&#62;

 &#60;a4j:keepAlive beanName="rascunhoMB" /&#62;

 &#60;ui:composition template="/template/template.xhtml"&#62;
 &#60;ui:define name="corpo"&#62;
 &#60;h:form&#62;
 &#60;rich:messages /&#62;

 &#60;fieldset&#62;
 &#60;legend&#62;Rascunho&#60;/legend&#62;
 &#60;h:panelGrid columns="2"&#62;
 &#60;h:outputLabel for="titulo" value="Título "  /&#62;
 &#60;h:outputLabel id="titulo" readonly="true" value="#{rascunhoMB.rascunho.titulo}" style=" width : 254px;"/&#62;

 &#60;h:outputLabel for="data" value="Data "  /&#62;
 &#60;h:outputLabel id="data" readonly="true" value="#{rascunhoMB.rascunho.data}" style=" width : 254px;"&#62;
 &#60;f:convertDateTime pattern="dd/MM/yyyy" /&#62;
 &#60;/h:outputLabel&#62;
 &#60;/h:panelGrid&#62;    

 &#60;h:panelGrid columns="1"&#62;
 &#60;rich:editor theme="advanced" autoResize="true" value="#{rascunhoMB.rascunho.conteudo}" height="300" width="822" readonly="true"/&#62;
 &#60;/h:panelGrid&#62;                

 &#60;a4j:commandButton value="Salvar " action="#{rascunhoMB.save}" styleClass="botoes"/&#62;
 &#60;h:commandButton value="Voltar " action="toGerenciaRascunhos" immediate="true" styleClass="botoes"/&#62;
 &#60;/fieldset&#62;
 &#60;/h:form&#62;
 &#60;/ui:define&#62;
 &#60;/ui:composition&#62;
&#60;/html&#62;</pre>
</blockquote>
<h2><span style="color:#888888;">Importando o projeto</span></h2>
<ol>
<li><span style="color:#000000;">Baixe o projeto completo &#62;&#62;<a href="http://www.4shared.com/file/132691995/170230d9/rich_editor_facelets.html">aqui</a>&#60;&#60;;</span></li>
<li><span style="color:#000000;">Descompacte o projeto no seu <em>workspace</em>;</span></li>
<li><span style="color:#000000;">No Eclipse vá em: File –&#62; Import –&#62; General – Existing Projects into Workspace –&#62; Next –&#62; Selecione o projeto descompactado no workspace –&#62; Finish.</span></li>
</ol>
<h2><span style="color:#888888;">Criando o banco de dados</span></h2>
<ol>
<li><span style="color:#000000;">Com o MySQL instalado e configurado com usuário: <strong>root</strong> e senha: <strong>root</strong> crie um novo schema com o nome de <strong><em>jsf</em></strong>.</span></li>
<li><span style="color:#000000;">Execute a classe <em>br.com.serjaum.util.<strong>GerarTabelas.java. </strong>E</em>ssa classe criará as tabelas que foram mapeadas no arquivo <em>hibernate.cfg.xml</em>, no caso a classe <strong>Rascunho</strong> terá uma tabela correspondente com o nome de <strong>rascunho</strong> no nosso banco de dados.</span></li>
</ol>
<h2><span style="color:#888888;">Resultado</span></h2>
<p style="text-align:center;"><span style="color:#888888;"><img class="aligncenter size-full wp-image-853" title="resultado1" src="http://serjaum.wordpress.com/files/2009/09/resultado11.png" alt="resultado1" width="622" height="521" /></span></p>
<p style="text-align:center;"><span style="color:#888888;"><img class="aligncenter size-full wp-image-854" title="resultado2" src="http://serjaum.wordpress.com/files/2009/09/resultado21.png" alt="resultado2" width="622" height="521" /></span></p>
<p style="text-align:center;"><span style="color:#888888;"><br />
</span></p>
<p style="text-align:left;"><span style="color:#888888;"><span style="color:#000000;">Até o próximo post!</span><br />
</span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[DBUnit in Eclipse]]></title>
<link>http://cvalcarcel.wordpress.com/2009/09/05/dbunit-in-eclipse/</link>
<pubDate>Sat, 05 Sep 2009 19:29:24 +0000</pubDate>
<dc:creator>cvalcarcel</dc:creator>
<guid>http://cvalcarcel.wordpress.com/2009/09/05/dbunit-in-eclipse/</guid>
<description><![CDATA[Just the other day I was wondering how DBUnit was doing. As a former consultant I used to use DBUnit]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Just the other day I was wondering how <a href="http://dbunit.sourceforge.net/">DBUnit</a> was doing. As a former consultant I used to use DBUnit along with various <a href="http://www.junit.org/">JUnit</a> extensions on a regular basis.</p>
<p>Given that <a href="http://eclipse.org/">Eclipse</a> has moved on, JUnit has moved on and DBUnit has moved on I thought I would present a straightforward example of how to use DBUnit with JUnit 4.0 and Eclipse.</p>
<p>Not that much has changed therefore there is not going to be a lot of hand holding here.</p>
<h2>Assumptions</h2>
<p><a href="http://eclipse.org/downloads/">Eclipse 3.5</a><br />
JUnit 4.0 &#8211; included with Eclipse<br />
<a href="http://sourceforge.net/projects/dbunit/files/dbunit/2.4.5/dbunit-2.4.5.jar/download">DBUnit 2.4.5</a><br />
<a href="http://www.slf4j.org/dist/slf4j-1.5.8.zip">SLF4J 1.5.8</a> &#8211; DBUnit needs this<br />
<a href="http://sourceforge.net/projects/hsqldb/files/hsqldb/hsqldb_1_8_0/hsqldb_1_8_0_10.zip/download">HSQL DB 1.8.0</a></p>
<p>I implemented this example on <a href="http://www.kubuntu.org/">Kubuntu</a> 9.10, if that makes any difference.</p>
<p>If you are new to Eclipse then just download any version that seems reasonable as long as it includes a Java development environment.</p>
<h2>The Easy Part</h2>
<p>Make sure all of the above software is available somewhere on your machine. If not, install all the software in your favorite places.</p>
<p>Start Eclipse.</p>
<h2>The Short Version</h2>
<ol>
<li>Start your database</li>
<li>Create a Java Project</li>
<li>Add DBUnit to your classpath</li>
<li>Write and run a database test
<ul>
<li>Create initial and expected dataset files</li>
<li>Extend DBTestCase (inheritance) or use a JUnit class (composition)</li>
<li>Implement your test methods</li>
</ul>
</li>
</ol>
<h2>The Longer Version</h2>
<h3>Start your database</h3>
<p>I don&#8217;t have a database to run so I downloaded and installed HSQL. To run the HSQL server, which I prefer in examples, open a command window, go to the HSQL folder and run:</p>
<p>java -cp lib/hsqldb.jar org.hsqldb.Server -database.0 file:hiddenclause -dbname.0 xdb</p>
<p>In this case the database name is <code>xdb</code> with the database files named <code>hiddenclause.*</code>. Call your files whatever. I will add test data later.</p>
<p>My Eclipse default configuration includes:<br />
Source folder name: <code>src</code><br />
Output folder name: <code>classes</code></p>
<p>Default execution environment: JavaSE-1.6</p>
<h3>Create a Java Project</h3>
<p>Create a Java Project named <code>DBUnitExample</code>. &#8216;Nuff said.</p>
<h3>Add DBUnit to your classpath</h3>
<p>Once the project appears in the <strong>Package Explorer</strong>, right click on the project name and select Properties &#8211;&#62; Java Build Path &#8211;&#62; Libraries. Click <strong>Add External JARs</strong> and add the DBUnit JAR file, in this case <strong>dbunit-2.4.5.jar</strong>, to the list of libraries in the classpath. Yes, you could also have done this when you first created the project.</p>
<p>Add:<br />
- <code>slf4j-api-1.5.8.jar</code><br />
- <code>slf4j-simple-1.5.8.jar</code><br />
- <code>hsqldb.jar</code><br />
to the classpath as well.</p>
<p>Click OK to close the Properties window.</p>
<h3>Write and run a database test</h3>
<h4>Add Test Data</h4>
<p>As running a test on a fresh database is a little difficult start the HSQL Database Manager from another shell (in the HSQL directory):</p>
<p><code>java -cp lib/hsqldb.jar org.hsqldb.util.DatabaseManager</code></p>
<p>In the Connect window enter:<br />
Setting Name: <strong>hiddenclause example</strong><br />
Type: <strong>HSQL Database Engine Server</strong><br />
Driver: <strong>org.hsqldb.jdbcDriver</strong><br />
URL: <strong>jdbc:hsqldb:hsql://localhost/xdb</strong><br />
User: <strong>sa</strong><br />
Password: [leave blank]</p>
<p>Click <strong>OK</strong>.</p>
<p>Almost done. Select <strong>Options &#8211;&#62; Insert Test Data.</strong> Now we have 4 tables worth of data to test with. Run a delete on the CUSTOMER table so that is is empty.</p>
<p>Close the Database Manager.</p>
<h4>Write a Database Test</h4>
<p>The steps for writing a DBUnit test are:<br />
1. Create initial and expected dataset files<br />
2. Extend <code>DBTestCase</code> (inheritance) or use a JUnit class (composition)<br />
3. Implement your test methods</p>
<p>Once you get comfortable with that the additional steps are:<br />
1. Create initial and expected dataset files<br />
2. Extend <code>DBTestCase</code> (inheritance) or use a JUnit class (composition)<br />
3. Implement <code>getSetUpOperation()</code> and <code>getTearDownOperation()</code> (optional)<br />
4. Override <code>setUpDatabaseConfig()</code> (optional)<br />
5. Implement your test methods</p>
<p>We&#8217;ll just do the first one using the test data created by HSQL.</p>
<h5>Create initial and expected dataset files</h5>
<p>The DBUnit dataset can come from anywhere (files, databases, spreadsheets, etc.). Where the data comes from is hidden behind the class that implements IDataSet. For this example, we will use XML datasets.</p>
<p>Here is the initial dataset file:<br />
customer-init.xml</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;dataset.
    &lt;CUSTOMER /&gt;
&lt;/dataset&gt;
</pre>
<p>Here is the expected dataset (what we expect to find in the database after executing some code):</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;dataset&gt;
     &lt;CUSTOMER ID=&quot;1&quot;
               FIRSTNAME=&quot;John&quot;
               LASTNAME=&quot;Smith&quot;
               STREET=&quot;1 Main Street&quot;
               CITY=&quot;Anycity&quot; /&gt;
&lt;/dataset&gt;
</pre>
<h5>Extend DBTestCase (inheritance) or use a JUnit class (composition)</h5>
<p>The first version of CustomerTest will inherit from the DBUnit class DBTestCase. That is the recommended way of creating a DBUnit test. It uses the JUnit 3.8.2 classes which still works even with the JUnit 4.0 JAR file.</p>
<pre class="brush: java;">
public class CustomerTest extends DBTestCase {
...
    @Override
    protected IDataSet getDataSet() throws Exception {
        ...
    }
}
</pre>
<p>The getDataSet() method is called to initialize the database before the test. Consider it part of your setup logic. Let&#8217;s load the initialization dataset.</p>
<pre class="brush: java;">
    @Override
    protected IDataSet getDataSet() throws Exception {
        return new FlatXmlDataSet(
                 new FileInputStream(&quot;customer-init.xml&quot;));
    }</pre>
<p>There are a number of properties that need to be set prior to DBUnit doing its magic. You can set those properties in the constructor:</p>
<pre class="brush: java;">
    public CustomerTest(String name) {
        super(name);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
          &quot;org.hsqldb.jdbcDriver&quot;);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
          &quot;jdbc:hsqldb:hsql://localhost/xdb&quot;);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
          &quot;sa&quot;);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
          &quot;&quot;);

        _customerFactory = CustomerFactory.getInstance();
    }
</pre>
<p>In real life you would set the driver name, connection URL and username and password to their appropriate values.</p>
<h5>Implement your test methods</h5>
<p>For this example, we are going to test an insert into the db.</p>
<pre class="brush: java;">
    public void testInsert() throws Exception {
        // insert a customer into the database
        Customer customer = _customerFactory.create(&quot;John&quot;, &quot;Smith&quot;);
        customer.setStreet(&quot;1 Main Street&quot;);
        customer.setCity(&quot;Anycity&quot;);
        _customerFactory.update(customer);
...
</pre>
<p>The code for the <code>CustomerFactory</code> and <code>Customer</code> are at the end of this post.</p>
<p>The data that has just been entered into the database becomes your actual assertable values. Go get them.</p>
<pre class="brush: java;">
        // get the actual table values
        IDatabaseConnection connection = getConnection();
        IDataSet databaseDataSet = connection.createDataSet();
        ITable actualTable = databaseDataSet.getTable(&quot;CUSTOMER&quot;);
</pre>
<p>The values defined in customer-expected.xml are what you expect the values to be. Go get them.</p>
<pre class="brush: java;">
        // get the expected table values
        IDataSet expectedDataSet = new FlatXmlDataSet(
                                          new FileInputStream(&quot;customer-expected.xml&quot;));
        ITable expectedTable = expectedDataSet.getTable(&quot;CUSTOMER&quot;);
</pre>
<p>Check the actual against the expected and complain or not as the case may be.</pre>
<p>Assertion.assertEquals(expectedTable, actualTable);<br />
}[/sourcecode]<br />
A version that uses a JUnit class as a wrapper around the DBUnit code looks like this:</p>
<pre class="brush: java;">
/**
 * This is an example only! Use it for anything else at your own risk!
 * You have been warned! Coder/user beware!
 *
 * copyright 2009 Carlos Valcarcel
 */
package hiddenclause.example.dbunit;

import java.io.FileInputStream;

import org.dbunit.Assertion;
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author carlos
 */
public class CustomerJunitTest {

    private CustomerFactory _customerFactory;

    private IDatabaseTester databaseTester;

    @Before
    public void setUp() throws Exception {
        databaseTester = new JdbcDatabaseTester(&quot;org.hsqldb.jdbcDriver&quot;,
                                                &quot;jdbc:hsqldb:hsql://localhost/xdb&quot;,
                                                &quot;sa&quot;, &quot;&quot;);
        // initialize your dataset here
        IDataSet dataSet = new FlatXmlDataSet(new FileInputStream(&quot;customer-init.xml&quot;));

        databaseTester.setDataSet(dataSet);

        // will call default setUpOperation
        databaseTester.onSetup();

        _customerFactory = CustomerFactory.getInstance();
    }

    @Test
    public void testInsert() throws Exception {
        // insert a customer into the database
        Customer customer = _customerFactory.create(&quot;John&quot;, &quot;Smith&quot;);
        customer.setStreet(&quot;1 Main Street&quot;);
        customer.setCity(&quot;Anycity&quot;);
        _customerFactory.update(customer);

        // get the actual table values
        IDatabaseConnection connection = databaseTester.getConnection();
        IDataSet databaseDataSet = connection.createDataSet();
        ITable actualTable = databaseDataSet.getTable(&quot;CUSTOMER&quot;);

        // get the expected table values
        IDataSet expectedDataSet = new FlatXmlDataSet(
                                          new FileInputStream(&quot;customer-expected.xml&quot;));
        ITable expectedTable = expectedDataSet.getTable(&quot;CUSTOMER&quot;);

        Assertion.assertEquals(expectedTable, actualTable);

    }

    @After
    public void tearDown() throws Exception {
        databaseTester.onTearDown();
    }
}</pre>
<p>Things to notice:<br />
- less configuration (the <code>System.setProperty()</code> calls are gone)<br />
- explicit creation of a <code>IDatabaseTester</code> object<br />
- explicit call to <code>databaseTester.onSetup()</code><br />
- explicit call to <code>databaseTester.onTearDown()<br />
</code></p>
<h4>Run the Database Test</h4>
<p>With all the pieces in place it is now safe to run the <code>CustomerTest</code> DBUnit class. You will probably see some warning messages in the <strong>Console</strong> view about the data type factory being incorrect. You can safely ignore that error for this example. In real life you probably want to instantiate a new <code>DataTypeFactory</code> based on the database you are using.</p>
<p>If any of the above does not quite work as described let me know and I will update the above explanation.</p>
<h2>The Code</h2>
<p>customer-init.xml</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;dataset&gt;
    &lt;CUSTOMER /&gt;
&lt;/dataset&gt;
</pre>
<p>customer-expected.xml</p>
<pre class="brush: java;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;dataset&gt;
    &lt;CUSTOMER ID=&quot;1&quot;
              FIRSTNAME=&quot;John&quot;
              LASTNAME=&quot;Smith&quot;
              STREET=&quot;1 Main Street&quot;
              CITY=&quot;Anycity&quot; /&gt;
&lt;/dataset&gt;
</pre>
<p>CustomerTest.java</p>
<pre class="brush: java;">
/**
 * This is an example only! Use it for anything else at your own risk!
 * You have been warned! Coder/user beware!
 *
 * copyright 2009 Carlos Valcarcel
 */
package hiddenclause.example.dbunit;

import java.io.FileInputStream;

import org.dbunit.Assertion;
import org.dbunit.DBTestCase;
import org.dbunit.PropertiesBasedJdbcDatabaseTester;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.xml.FlatXmlDataSet;

/**
 * @author carlos
 */
public class CustomerTest extends DBTestCase {

    private CustomerFactory _customerFactory;

    public CustomerTest(String name) {
        super(name);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
          &quot;org.hsqldb.jdbcDriver&quot;);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
          &quot;jdbc:hsqldb:hsql://localhost/xdb&quot;);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
          &quot;sa&quot;);
        System.setProperty(
          PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
          &quot;&quot;);

        _customerFactory = CustomerFactory.getInstance();
    }

    public void testInsert() throws Exception {
        // insert a customer into the database
        Customer customer = _customerFactory.create(&quot;John&quot;, &quot;Smith&quot;);
        customer.setStreet(&quot;1 Main Street&quot;);
        customer.setCity(&quot;Anycity&quot;);
        _customerFactory.update(customer);

        // get the actual table values
        IDatabaseConnection connection = getConnection();
        IDataSet databaseDataSet = connection.createDataSet();
        ITable actualTable = databaseDataSet.getTable(&quot;CUSTOMER&quot;);

        // get the expected table values
        IDataSet expectedDataSet = new FlatXmlDataSet(
                                          new FileInputStream(&quot;customer-expected.xml&quot;));
        ITable expectedTable = expectedDataSet.getTable(&quot;CUSTOMER&quot;);

        Assertion.assertEquals(expectedTable, actualTable);

    }
    /*
     * (non-Javadoc)
     * @see org.dbunit.DatabaseTestCase#getDataSet()
     */
    @Override
    protected IDataSet getDataSet() throws Exception {
        return new FlatXmlDataSet(
                 new FileInputStream(&quot;customer-init.xml&quot;));
    }

}
</pre>
<p>CustomerFactory.java</p>
<pre class="brush: java;">
/**
 * This is an example only! Use it for anything else at your own risk!
 * You have been warned! Coder/user beware!
 *
 * copyright 2009 Carlos Valcarcel
 */
package hiddenclause.example.dbunit;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author carlos
 *
 */
public class CustomerFactory {

    static {
        try {
            Class.forName(&quot;org.hsqldb.jdbcDriver&quot;);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static CustomerFactory getInstance()
    {
        return new CustomerFactory();
    }

    public Customer create(String firstName, String lastName) {
        return new Customer(1, firstName, lastName);
    }

    public void update(Customer customer) throws SQLException {
        Connection connection = DriverManager.getConnection(&quot;jdbc:hsqldb:hsql://localhost/xdb&quot;);
        String sql = &quot;insert into customer (id, firstname, lastname, street, city) values (&quot;
                   + customer.getId() + &quot;, &quot;
                   + &quot;'&quot; + customer.getFirstName() + &quot;', &quot;
                   + &quot;'&quot; + customer.getLastName() + &quot;', &quot;
                   + &quot;'&quot; + customer.getStreet() + &quot;', &quot;
                   + &quot;'&quot; + customer.getCity() + &quot;'&quot;
                   + &quot;)&quot;;

        Statement stmt = connection.createStatement();
        stmt.execute(sql);
        if (stmt.getUpdateCount() != 1) {
            throw new SQLException(&quot;Insert failed!&quot;);
        }
    }

}
</pre>
<p>Customer.java</p>
<pre class="brush: java;">
/**
 * This is an example only! Use it for anything else at your own risk!
 * You have been warned! Coder/user beware!
 *
 * copyright 2009 Carlos Valcarcel
 */
package hiddenclause.example.dbunit;

/**
 * @author carlos
 *
 */
public class Customer {

    private int _id;
    private String _firstName;
    private String _lastName;
    private String _street;
    private String _city;

    public Customer(int id, String firstName, String lastName) {
        _id = id;
        _firstName = firstName;
        _lastName = lastName;
    }

    public int getId() {
        return _id;
    }

    public String getFirstName() {
        return _firstName;
    }

    public String getLastName() {
        return _lastName;
    }

    public String getStreet() {
        return _street;
    }

    public String getCity() {
        return _city;
    }

    public void setStreet(String street) {
        _street = street;
    }

    public void setCity(String city) {
        _city = city;
    }

}
</pre>
</div>]]></content:encoded>
</item>

</channel>
</rss>
