Test Data Builders

Posted in Unit Testing on December 28th, 2011 by norman – Be the first to comment

I have been programming for a long time now for various fortune 500 companies and in all cases there has been some attempt at test driven development. This has mostly failed due to management and/or developers not being 100% behind it with tests usually written after the fact and badly maintained if at all.

Luckily at my current job I have been leading the development effort and was able to start unit tests from the beginning. However one problem was apparent from the get go. Our tests had too many mistakes. This was mostly due to repetitive code to set object properties and/or use of cut and paste. Having used the Object Mother Pattern before, this was my first solution. However I had another problem. I needed my BAs to review the unit tests and make sure that they reflected the various use cases. My BAs are non-technical and at the sight of Java code they would put their hands up in the air and walk away.

Searching for ‘alternatives to the Object Mother Pattern’ I came across the following link: Test Data Builders: an alternative to the Object Mother pattern and I had my answer. Not only did I get better unit tests as a result but here was something I could show to my BAs without making them break into sweat.

Certainly this is better:

        Asset c124 = new CertificateBuilder()
        	.withCertificateNumber(124)
        	.withQuantity("10000")
        	.withTransId(124)
        	.withTaxLot(
        		new TaxLotBuilder()
        		    .withTransId(125)
        		    .withCoveredIndicator(Constants.COVERED_IND)
        		    .withEffectiveDate(20120103)
        		    .withQuantity("10000")
        		    .withCostBasisPerShare("10.000")
        		    .build())
        	.build();

Than this:

        taxLot = new TaxLot();
        taxLot.setTaxLotId(124);
        taxLot.setAcqEffectiveDate(20120103);
        taxLot.setCoveredIndicator(Constants.COVERED_IND);
        taxLot.setQuantity(new BigDecimal(10000));
        taxLot.setCostBasisPerShare(new BigDecimal("10.000"));

        Asset c124 = TestHelper.createCertificate(124, "C", "124", new BigDecimal("10000"));
             c124.getAssociatedTaxLots().add(taxLot);