Angel \”Java\” Lopez on Blog

February 14, 2012

TDD: Links, News and Resources (2)

Previous Post

If TDD is about design why do I need it?
http://programmers.stackexchange.com/questions/102649/if-tdd-is-about-design-why-do-i-need-it/103276#103276

How to Introduce a Test Driven Mindset
http://www.agileadvice.com/2011/09/07/uncategorized/how-to-introduce-a-test-driven-mindset/

Better is Better
http://www.infoq.com/presentations/Better-is-Better

Karate Chop Kata in C#
http://www.youtube.com/watch?v=D3BbjRo2MxY&feature=related

caolan / nodeunit
https://github.com/caolan/nodeunit
Easy unit testing in node.js and the browser, based on the assert module.

mfncooper / mockery
https://github.com/mfncooper/mockery
Simplifying the use of mocks with Node.js

On The Testing In Clojure Debate
http://philcalcado.com/2011/10/08/on_the_testing_in_clojure_debate.html
Recently, Rich Hickey said something at the Strange Loop conference comparing Test-Driven Development to driving a car around banging into the guard rails…

Simple Made Easy
http://www.infoq.com/presentations/Simple-Made-Easy

Vows
http://vowsjs.org/
Asynchronous behaviour driven development for Node.

qmock
http://code.google.com/p/qmock/
A JavaScript mocking library

Writing a Business-Oriented JavaScript Web Application
http://msdn.microsoft.com/en-gb/magazine/hh475811.aspx

Tests Unitarios. Cuándo usarlos y pistas para conseguir un sistema robusto
http://www.etnassoft.com/category/tdd-2/

Clean Code Episode VI – TDD – Part 1
http://www.cleancoders.com/codecast/clean-code-episode-6-part-1/show

How to write and unit-test universal JavaScript modules (browser, Node.js)
http://www.2ality.com/2011/08/universal-modules.html

Bridging the module gap between Node.js and browsers
http://www.2ality.com/2011/11/module-gap.html

Science or Snake Oil: Empirical software engineering
http://se9book.wordpress.com/2011/08/29/science-or-snake-oil-empirical-software-engineering/

How do I Jasmine: a tutorial
http://evanhahn.com/?p=181
Jasmine is a unit testing framework for JavaScript.

BDD and TDD for node.js?
http://stackoverflow.com/questions/4706020/bdd-and-tdd-for-node-js

Testing Backbone applications with Jasmine and Sinon – Part 1
http://tinnedfruit.com/2011/03/03/testing-backbone-apps-with-jasmine-sinon.html

Continuos Tests
http://www.continuoustests.com/

The Land that Scrum Forgot
http://scrumalliance.org/articles/300-the-land-that-scrum-forgot
We need to go fast, and we need to stay clean so we can keep going fast.  How can we incent the team to achieve both goals?  Simple.  We measure both and reward them equally…
We can measure messes by implementing engineering disciplines and practices like Test Driven Development (TDD), Continuous Integration, Pair Programming, Collective Ownership, and Refactoring; i.e. the engineering practices of eXtreme Programming (XP)

TDD 101 Learning Series – Beginning Test-Driven Development in a Legacy System Webinar Recording
http://blogs.seapine.com/2011/08/tdd-101-learning-series-%E2%80%93-beginning-test-driven-development-in-a-legacy-system-webinar-recording/

Practical Testing Techniques for Windows Azure Applications
http://www.devproconnections.com/article/cloud-computing2/cloud-test-windows-azure-136179
How to use unit testing and mocking to build tests for an Azure-hosted website

Clojure FizzBuzz
http://tech.puredanger.com/2011/06/30/clojure-fizzbuzz/

The powershell continuously watch for file changes in a directory, then it executes PhantomJs with the Run-Qunit.js attached to your htm qunit test harness
https://gist.github.com/1125265

Growing instant legacy code with TDD and Mocks
http://theitriskmanager.wordpress.com/2011/07/05/growing-instant-legacy-code-with-tdd-and-mocks/

Test Driven Development (TDD) and Windows Phone 7
http://simonguest.com/2010/10/18/test-driven-development-tdd-and-windows-phone-7/

Test-Driven Development Is Not Slower
http://trycatchfail.com/blog/post/Test-Driven-Development-Is-Not-Slower.aspx

TDD: Keeping test intent when using test builders
http://www.markhneedham.com/blog/2009/09/20/tdd-keeping-test-intent-when-using-test-builders/

C#: Builder pattern still useful for test data
http://www.markhneedham.com/blog/2009/01/21/c-builder-pattern-still-useful-for-test-data/

TDD Kata in C++: String Calculator – Interactions
http://vimeo.com/26177491

TDD Kata 2 – Interactions
http://osherove.com/tdd-kata-2/

The thing about TDD and pretty pictures
http://looseneurons.com/2011/06/25/the-thing-about-tdd-and-pretty-pictures/

How We Built the Software that Processes Billions in Payments
http://www.braintreepayments.com/inside-braintree/how-we-built-the-software-that-processes-billions-in-payments

My Links
http://delicious.com/ajlopez/tdd

More links about agile, TDD, XP, software development, programming languages are coming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

October 8, 2011

Agile: Links, News and Resources (1)

Filed under: Agile Software Devevelopment, Links — ajlopez @ 11:01 am

As usual, when I work with some technology, methodology, or study a topic, I make a trace of links that I found in my way. These are some of my links about Agile:

Agile Meets Stephen Covey
http://www.slideshare.net/gantjd/agile-meets-stephen-covey

InfoQ: The Accidental Agilist: A Personal Look Back at 10 Years of the Agile Manifesto
http://www.infoq.com/articles/Accidental-Agilist

InfoQ: Scaling Lean & Agile: Large, Multisite or Offshore Delivery
http://www.infoq.com/presentations/Large-Multisite-or-Offshore-Delivery

Code & Beyond: Video: Comunicación no violenta, con Ingrid Astiz
http://www.codeandbeyond.org/2011/07/video-comunicacion-no-violenta-con.html

InfoQ: Everything I’ve Ever Learned, I Learned from Failure
http://www.infoq.com/presentations/I-Learned-from-Failure

InfoQ: Application Build and Continuous Integration Patterns
http://www.infoq.com/news/2011/04/build-ci-patterns

InfoQ: How To Split User Stories
http://www.infoq.com/news/2011/04/how-to-split-user-stories

Perspectives – 30 June 2011 | www.thoughtworks.com | Continuous Delivery
http://www.thoughtworks.com/perspectives/30-06-2011-continuous-delivery

Code & Beyond: Video: ¿Qué esperas de Agile? con Federico Zuppa
http://www.codeandbeyond.org/2011/07/video-que-esperas-de-agile-con-federico.html

How We Built the Software that Processes Billions in Payments
http://www.braintreepayments.com/inside-braintree/how-we-built-the-software-that-processes-billions-in-payments

InfoQ: Agile Schools: How Technology Saves Education (Just Not the Way We Thought it Would)
http://www.infoq.com/articles/agile-schools-education

Najaraba.com: Software libre, metodologías ágiles y más.: Mi "elevator pitch" del agilismo
http://najaraba.blogspot.com/2011/06/mi-elevator-pitch-del-agilismo.html

Amazon.com: Agile Principles, Patterns, and Practices in C# (9780131857254): Robert C. Martin, Micah Martin: Books
http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258

AgileBox – AgileBox
http://agilebox.lebrijo.com/
AgileBox is a virtualBox appliance to be mounted in your LAN, ready to help developers to adopt the Agile programming techniques and project management best practices

Xtreme Game Programming Method – Game Developers Web | Game Developers Web
http://www.gamedevelopersweb.com/xtreme-game-programming-method/

Visual Management for Agile teams – a session at Øredev 2010
http://oredev.org/2010/sessions/visual-management-for-agile-teams

Exploration Through Example » Blog Archive » Screen pairing
http://www.exampler.com/blog/2008/12/10/screen-pairing/

Kanban and Tragedy of the Commons | AvailAgility
http://availagility.co.uk/2011/06/11/kanban-and-tragedy-of-the-commons/

InfoQ: From Months to Minutes – Upping the Stakes
http://www.infoq.com/presentations/From-Months-to-Minutes

Las Cronicas de la Programacion
http://theprogrammingchronicles.com/
http://theprogrammingchronicles.com/tag/agile/

Agile #scale by Techdoer Times
http://techdoertimes.com/agile/agile-scale

InfoQ: Large-Scale Agile Design & Architecture: Ways of Working
http://www.infoq.com/articles/large-scale-agile-design-and-architecture

My Links
http://www.delicious.com/ajlopez/agile

More Agile, Scrum links are coming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

August 2, 2011

TDD: Links, News and Resources (1)

Next Post

You know, I’m a big fan of Test-Driven Development. I think that any production code should be written using TDD. These are some of my links.

TDD = Test-Driven Development
http://en.wikipedia.org/wiki/Test-driven_development

Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or ‘rediscovered’ the technique, stated in 2003 that TDD encourages simple designs and inspires confidence.[1]

Test-driven development is related to the test-first programming concepts of extreme programming, begun in 1999,[2] but more recently has created more general interest in its own right.[3]

Programmers also apply the concept to improving and debugging legacy code developed with older techniques.[4]

TDD for unbelievers | Agile Zone
http://agile.dzone.com/news/tdd-unbelievers

Real Developers Don’t Need Unit Tests
http://www.wakaleo.com/resources/presentations/288-real-developers-dont-need-unit-tests

Interaction-based testing and stable expectations – Vagif Abilov’s blog on .NET
http://bloggingabout.net/blogs/vagif/archive/2010/08/08/interaction-based-testing-and-stable-expectations.aspx

TDD Adoption Strategies Article | Agile Pain Relief
http://agilepainrelief.com/notesfromatooluser/2009/01/tdd-adoption-strategies-article.html

TDD adapted for mere mortals | Agile Zone
http://agile.dzone.com/news/tdd-adapted-mere-mortals

Purple Plutonium: Are TDD and Polyglot Programming a Poor Combination?
http://purpleplutonium.blogspot.com/2011/06/are-tdd-and-polyglot-programming-poor.html?spref=tw

HunabKu: C# OAuth for TESTardi
http://fabiomaulo.blogspot.com/2011/06/c-oauth-for-testardi.html

See? We Don’t Need a Database … Yet | xProgramming.com
http://xprogramming.com/articles/see-we-dont-need-a-database-yet/

But We Need a Database … Don’t We? | xProgramming.com
http://xprogramming.com/articles/but-we-need-a-database-dont-we/

The various meanings of TDD – Blog – Osherove
http://osherove.com/blog/2007/10/8/the-various-meanings-of-tdd.html

DirigidoPorTests
http://www.dirigidoportests.com/

Getting Started with TypeMock Isolator (in VS2010) | The McDev Blog
http://www.mcdev.za.net/2011/06/getting-started-with-typemock-isolator-in-vs2010/

Escribiendo mejores Test II
http://weblogs.javahispano.org/artesanodeprimera/entry/escribiendo_mejores_test_ii

Test Driven Development in PHP | Web Builder Zone
http://css.dzone.com/news/test-driven-development-php

How to Start Unit Testing .NET Projects: A Guide to Writing Unit Tests
http://www.typemock.com/unit-testing-dot-net

pyDoubles Framework | Test doubles framework for the Python platform
http://www.pydoubles.org/

planetgeek.ch» Clean Code and Clean TDD Cheat Sheets
http://www.planetgeek.ch/2011/01/04/clean-code-and-clean-tdd-cheat-sheets/

InfoQ: Representing Agile Testing
http://www.infoq.com/news/2011/04/representing-agile-testing

JavaScript: Unit testing asynchronous functions : Algorithms for the masses – julian m bucknall
http://blog.boyet.com/blog/javascriptlessons/javascript-unit-testing-asynchronous-functions/

Script Junkie | jQuery Test-Driven Development
http://msdn.microsoft.com/en-us/scriptjunkie/ff452703.aspx

andybeeching/qmock – GitHub
https://github.com/andybeeching/qmock
QMock is a standalone, lightweight mocking framework that facilitates the testing of JavaScript programs

QUnit – jQuery JavaScript Library
http://docs.jquery.com/QUnit

Script Junkie | Test Driven Development: Top-Down or Bottom-Up?
http://msdn.microsoft.com/en-us/scriptjunkie/gg650426.aspx

TDD for Managers with J.B. Rainsberger on Vimeo
http://vimeo.com/4396476

Test-Driven Development and Embracing Failure | Steve Freeman
http://www.m3p.co.uk/blog/2011/04/25/tdd-embracing-failure/

My Links:
http://www.delicious.com/ajlopez/tdd

My Posts:
http://ajlopez.wordpress.com/category/test-driven-development/

More links are upcoming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

June 24, 2011

Writing An Application Using TDD (Part 5) Adding Views

Previous Post
Next Post

Now I have some tests in place, I add some MVC views in this step. You can download the code from my AjCodeKatas Google Project, under trunk/AppTdd/Step04. So, this post has few new tests: it shows how we can build the interface AFTER the tests, and WITHOUT having a database or service layer, yet.

First, I added a new Site.master master page and style.css (borrowed from another ASP.NET MVC project)

I added a new Home controller:

Then, I added a view using the context menu over the Index method:

 

I modified the master page code, to have a new entry in its menu:

I added a new view associated to Index action in Subject controller:

I selected the “List” view content, and “Subject” as the type to use in the model.

But the controller method is:

public ActionResult Index()
{
    return View(subjects);
}

It uses a subject list, that is injected in the constructor by the tests:

public SubjectController(IList<Subject> subjects)
{
    this.subjects = subjects;
}

But wait! That list is injected by the tests. Now, I should inject in the normal process of the controller, in its parameter-less constructor:

public SubjectController()
    : this(Domain.Instance.Subjects)
{
}

I added a Domain.Instance to use as our in-memory domain:

public class Domain
{
    private static Domain instance = new Domain();
    private Domain()
    {
        this.Subjects = new List<Subject>()
        {
            new Subject() { Id = 1, Name = "Mathematics" },
            new Subject() { Id = 2, Name = "Physics" },
            new Subject() { Id = 3, Name = "Biology" },
            new Subject() { Id = 4, Name = "Literature" }
        };
    }
    public static Domain Instance { get { return instance; } }
    public IList<Subject> Subjects { get; set; }
}

I changed the links generated in the Index view from:

to use the Id property as primary key:

This is the result:

I created the other views using the Visual Studio “Add View…” wizard:

I had some missing actions, I wrote a new:

public ActionResult Edit(int id)
{
    var model = this.subjects.Where(s => s.Id == id).FirstOrDefault();
    return View(model);
}

With tests! ;-)

[TestMethod]
public void GetSubjectForEdit()
{
    IList<Subject> subjects = GetSubjects();
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Edit(1);
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(result, typeof(ViewResult));
    ViewResult viewResult = (ViewResult)result;
    Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(Subject));
    Subject model = (Subject)viewResult.ViewData.Model;
    Assert.AreEqual(1, model.Id);
    Assert.AreEqual("Mathematics", model.Name);
}

Curiously, I detected a “bad” test. I had written in my AddSubject test:

Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
Assert.AreEqual(4, subject.Id);

But the new id should be 5 (our testable list has 4 predefined subjects):

Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
Assert.AreEqual(5, subject.Id);

I fixed the code and the controller action, run the web application, and voila!

Main points:

- I am using an in-memory domain.

- The views run over the already tested actions

No service layer or persistence yet. Next steps: add more classes to domain (Books), service layer (using test), and some persistence.

Interesting related post about development with TDD without a database (or adding it after the tests) by @RonJeffries:

But We Need a Database … Don’t We? | xProgramming.com

See? We Don’t Need a Database … Yet | xProgramming.com

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

June 1, 2011

Writing An Application Using TDD (Part 4) Update and Insert

Previous Post
Next Post

In the previous post, I implemented the retrieve of one Subject data. No view is implemented yet. I’m writing the tests and then, implementing the code in the controller. It’s time to add a new Subject, using an action in the controller:

This was my first test:

[TestMethod]
public void AddSubject()
{
    IList<Subject> subjects = GetSubjects();
    Subject subject = new Subject() { Name = "Chemistry" };
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Create(subject);
    Assert.IsNotNull(result);
    Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
    Assert.AreNotEqual(0, subject.Id);
}

GetSubjects() is a helper method presented in the previous post. It returns a list of test subjects. I added a new action in the controller class, so the solution could be compiled:

public ActionResult Create(Subject subject)
{
    throw new NotImplementedException();
}

The test was red:

Then, I completed the action method, with the minimal code to pass the test:

public ActionResult Create(Subject subject)
{
   subject.Id = this.subjects.Max(s => s.Id);
   subjects.Add(subject);
   return RedirectToAction("Index");
}

But I want to redirect to the details view for the new item. I added assertions to the test:

RedirectToRouteResult redirect = (RedirectToRouteResult)result;
Assert.IsTrue(string.IsNullOrEmpty(redirect.RouteName));
Assert.IsTrue(redirect.RouteValues.ContainsKey("id"));
Assert.AreEqual(subject.Id, redirect.RouteValues["id"]);
Assert.IsTrue(redirect.RouteValues.ContainsKey("action"));
Assert.AreEqual("Details", redirect.RouteValues["action"]);

I changed the action code, only to comply with the new requirement:

public ActionResult Create(Subject subject)
{
    subject.Id = this.subjects.Max(s => s.Id);
    subjects.Add(subject);
    return RedirectToAction("Details", new { id = subject.Id });
}

Now, the test is red:

I followed a similar path to write and pass the test for update a subject. This is the current version of the test:

[TestMethod]
public void UpdateSubject()
{
    IList<Subject> subjects = GetSubjects();
    Subject literature = subjects.Where(s => s.Name == "Literature").FirstOrDefault();
    Subject subject = new Subject() { Name = "SciFi" };
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Update(literature.Id, subject);
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
    RedirectToRouteResult redirect = (RedirectToRouteResult)result;
    Assert.IsTrue(string.IsNullOrEmpty(redirect.RouteName));
    Assert.IsTrue(redirect.RouteValues.ContainsKey("id"));
    Assert.AreEqual(literature.Id, redirect.RouteValues["id"]);
    Assert.IsTrue(redirect.RouteValues.ContainsKey("action"));
    Assert.AreEqual("Details", redirect.RouteValues["action"]);
    Assert.IsTrue(subjects.Any(s => s.Name == "SciFi"));
    Assert.AreEqual(literature.Id, subjects.Where(s => s.Name == "SciFi").Single().Id);
}

The current controller action:

public ActionResult Update(int id, Subject subject)
{
    Subject toupdate = this.subjects.Where(s => s.Id == id).Single();
    toupdate.Name = subject.Name;
    return RedirectToAction("Details", new { id = id });
}

All the tests are green:

Some warnings: the tests are testing two ouputs: the change in the domain (a simple list) and the result action (an MVC concern). I should refactor (in an upcoming post) the implemention of the controller to separate the updates applied to the domain from the navigation results. I wrote the example in this way to show how to refactor the obtained code to have a better implementation. I could add tests that exercises the expected behavior when the subject to add is already in the domain, or the subject to update is missing.

Other note: there is no views yet. But I have the test in place to have confidence: when I added the views, I will have the expected behavior tested and in place.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

March 28, 2011

Writing an Application using TDD (Part 3) First Detail

First post
Next post
Previous post

Since the previous post, I applied the suggestions in comments from @MartinSalias and @theHumanFlag, thanks!. First, I renamed Genre class to Subject, using the refactoring features of Visual Studio:

public class Subject
{
    public string Name { get; set; }
}

Second, now the controller receives and process an IEnumerable<Subject>:

public class SubjectController : Controller
{
    private IEnumerable<Subject> subjects;
    public SubjectController()
    {
    }
    public SubjectController(IEnumerable<Subject> subjects)
    {
        this.subjects = subjects;
    }
    public ActionResult Index()
    {
        return View(subjects);
    }
}

I made the change with confidence, thanks to the test.

In this new step, I added an action: to get a Subject by Id. A new property Id in Subjec:

public class Subject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

I wrote the test:

[TestMethod]
public void GetSubjectForDetail()
{
    IEnumerable<Subject> subjects = new List<Subject>()
    {
        new Subject() { Id = 1, Name = "Mathematics" },
        new Subject() { Id = 2, Name = "Physics" },
        new Subject() { Id = 3, Name = "Biology" },
        new Subject() { Id = 4, Name = "Literature" }
    };
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Details(1);
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(result, typeof(ViewResult));
    ViewResult viewResult = (ViewResult)result;
    Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(Subject));
    Subject model = (Subject)viewResult.ViewData.Model;
    Assert.AreEqual(1, model.Id);
    Assert.AreEqual("Mathematics", model.Name);
}

The test didn’t compile. I created the action:

public ActionResult Details(int id)
{
    return View();
}

The test compile, but its result was red. Now, go for the green light:

public ActionResult Details(int id)
{
    var model = this.subjects.Where(s => s.Id == id).FirstOrDefault();
    return View(model);
}

I had two tests, that give a list of Subjects to the actions. I refactored the test to separate the creation of such list. I extracted the method:

private static IEnumerable<Subject> GetSubjects()
{
    IEnumerable<Subject> subjects = new List<Subject>()
    {
        new Subject() { Id = 1, Name = "Mathematics" },
        new Subject() { Id = 2, Name = "Physics" },
        new Subject() { Id = 3, Name = "Biology" },
        new Subject() { Id = 4, Name = "Literature" }
    };
    return subjects;
}

Now, the test code is:

[TestMethod]
public void GetSubjectInDetail()
{
    IEnumerable<Subject> subjects = GetSubjects();
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Details(1);
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(result, typeof(ViewResult));
    ViewResult viewResult = (ViewResult)result;
    Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(Subject));
    Subject model = (Subject)viewResult.ViewData.Model;
    Assert.AreEqual(1, model.Id);
    Assert.AreEqual("Mathematics", model.Name);
}

All tests in green!

As usual, the code is in my AjCodeKatas Google Project, under trunk/AppTdd/Step02)

Next steps: more actions, integrate views.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

March 22, 2011

Writing An Application Using TDD (Part 2) First List

Next post in this series
Previous post in this series

Thanks to a suggestion by @MartinSalias, I choose to develop a simple domain: my personal library, my books. In this first code iteration, I want to list the book genres: Physics, Mathematics, Biology, Literature… (similar to genres in MvcMusicStore by @jongalloway).

First, I created the ASP.NET MVC Solution (I’m using Visual Studio 2008) (the code for this post is in my AjCodeKatas Google Project, under trunk/AppTdd/Step01)

Then, I add a test project:

I added references to System.Web.Mvc and MyLibrary.Web, to be used in this test project.

I added a new test:

I cleaned the code of my first test class, removing unneeded methods. The result:

namespace MyLibrary.Web.Tests.Controllers
{
    using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    [TestClass]
    public class GenreControllerTests
    {
    }
}

Then, I added my first test:

        [TestMethod]
        public void GetGenres()
        {
            IList<Genre> genres = new List<Genre>()
            {
                new Genre() { Name = "Mathematics" },
                new Genre() { Name = "Physics" },
                new Genre() { Name = "Biology" },
                new Genre() { Name = "Literature" }
            };
            GenreController controller = new GenreController(genres);
            ActionResult result = controller.Index();
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            ViewResult viewResult = (ViewResult)result;
            Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(IList<Genre>));
            Assert.AreSame(genres, viewResult.ViewData.Model);
        }
		

The idea: create the controller, feed it with a list of genres, then invoke the Index action, and test the returned action result. The code didn’t compile: the controller didn’t exist, there were no Genre class. So, I wrote the Genre class in Model folder at MyLibrary.Web:

    public class Genre
    {
        public string Name { get; set; }
    }

A simple GenreController (added with right click on Model folder):

The wizard created this code:

    public class GenreController : Controller
    {
        //
        // GET: /Genre/
        public ActionResult Index()
        {
            return View();
        }
    }

I modified it to have an appropriate constructor:

    public class GenreController : Controller
    {
        public GenreController()
        {
        }
        public GenreController(IList<Genre> genres)
        {
        }
        public ActionResult Index()
        {
            return View();
        }
    }
	

Note that my intention was to compile the test: the list of genres are not used by the controller, yet. With all these changes, I could compile the solution, and run the test:

The result was:

The problem:

As expected. This is part of the TDD cycle: compile, red, and now, go for green.

I changed the controller behavior (the interface was already completed):

    public class GenreController : Controller
    {
        private IList<Genre> genres;
        public GenreController()
        {
        }
        public GenreController(IList<Genre> genres)
        {
            this.genres = genres;
        }
        public ActionResult Index()
        {
            return View(genres);
        }
    }

Now, the test result:

Triumph of mind over matter! ;-)

Now, time for refactoring. Well, I have not much for this now. I could improve same naming. The main missing piece: a view. Note: the controller is not prepared, yet, for production. It has no genre provider object.

Next steps: improve controller to use a view, add CRUD actions with tests, and views.

You could ask: where is the repository of genres? where is the database? what about a service layer? domain separation? Ok, all valid questions. My idea is to show, with incremental steps, how all those artifacts arise from improving the controllers, actions, by the force of new tests and refactoring. As I wrote in my previous post, this is a kind of top-down approach. In this case, the domain is simple, so I can start from the top presentation layer. After this simple example, I will switch to a less simple domain. In this case, we can start testing the domain, before any presentation layer.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

February 26, 2011

Writing an Application Using TDD (Part 1) Introduction

I’m writing a post series about writing an interpreter using TDD (Test-Driven Development). My intention is to show the use of TDD in our production code. Since my TDD adoption, I produce better code (I hope ;-) , and in less time (no more long debugging sessions ;-) . There are other benefits: if you have an application with TDD, you get good code coverage, and you write down the code use cases and expected results of the application. All that gives confidence to improve the application, maybe by other team. In my opinion, delivering an application with TDD is a plus for the end customer and for the healthy evolution of a successful software. You can get the same using simply test, but TDD adds the right iterative process to build production code.

But the interpreter example is like a “long code kata”. You can say: “Hey, it’s not the kind of code I write every day, for fun and money”. Yes, you are right. Then, it’s time to start a post series about writing an application.

I choose the technologies to use:

- .NET 3.5 (maybe, I’ll switch to 4.0)

- ASP.NET MVC 2 (again, I could use 3, at some point)

- Visual Studio 2008 (the other candidate is VS 2010), using its test features, as in my previous posts.

I should select the persistence technology. I’m thinking in NHibernate 3.x + Fluent NHibernate or ConfORM; the alternative is Entity Framework 4 with Code First.

There are two path to follow, in this iterative example:

- Simple domain: start to write presentation code and test, then an application layer, then the persistence stuff

- More complex domain: write the domain code and test, then add presentation, then the persistence.

The first one is a kind of “top-down” approach. It’s the opposite of I was using in my interpreter series (note the absence of mocks, stubs in my “bottom-up” approach, writing the expressions, commands, then part of the lexer, part of the parser, etc…). With this new way of doing TDD, I want to show the incremental build of functionality, even without having a database, persistence model, or other technical stuff. ASP.NET MVC and TDD able us to write the initial use cases in a simple way, in a simple domain, embracing an agile and incremental development. Another benefit is that we can deliver something “that works”, to get early feedback from customer.

After exploring such way of doing development with TDD, I will switch to a slightly more complex domain.  In such case, I will prefer to start writing the domain with tests, only to focus in the core of the application, adding some presentation stuff, but without spend much time in complex interface stuff.

The format of a post series is important: there are many examples of application code with TDD (many open source projects), but most of them are the “final” stage of a long path. Writing a simple example incrementally is a better way to grasp the TDD-style of doing software development.

Well, enough for today. This is an intro post, to present the idea, and starting the engines! Comments and suggestions, welcome.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

April 3, 2010

Beyond talking about Best Practices

This week, Hari Hariri (@hhariri) posted an interesting post:

Loved the show but I have toget back to the real world now

Hariri comments about his experience in two developers shows, where he gave talks. He wrote:

As usual, to set the context, I asked a series of questions regarding unit tests:

“How many of you know what a Unit Test is” – 80% put up their hand.

“How many of you do Unit Testing?” – 10% put up their hand.

“How many of you think Unit Testing is valuable?” – 80% put up their hand

The first show was for PHP developers. I guess that PHP developers used to work a bit different than other developers, at least in my times of PHP dev. Maybe, today, they have more tools to do the job. But the second show Hariri attended, was in front of 200 persons interested in software architecture.

Recently, in an internal talk in a software company, @MartinSalias asked similar questions, and the results were like Hariri’s ones. I didn’t take notes about the results, but in one of my talks, the results had the same bias: lot of people likes best practices, XP disciplines, etc… few ones were implemented them.

So, where is the problem? Hariri writes:

“A is good. I like A. I should do A. But I won’t do A”.

People identify themselves with the issues we talk about. They see the value writing automated tests and complying with design principles adds. They get excited, yet they don’t do it. Why?

I usually ask this question too, and the typical responses are:

1. Tight Schedules.

2. Decrease in Productivity. Drag and Drop is more productive

3. Customers want deliverables. Tests are not deliverables

and my all time favorite

4. “I’m paid to write code, not tests”.

Well, there are many reasons, each software developer and team have reasons to not apply TDD, automated testing, code reviews, pair programming, etc…

Let take one topic: TDD. Why people are not using TDD more in daily work? My guess:

- They know what is TDD, but they never practice it, they have many doubts

- If they work in a team, not all members knows about TDD, and the TDD-aware person didn’t practice or master TDD.

What they need? I think they need three points:

- Know the rationale behind TDD (they grasp this point in talks, articles, conference, books…)

- Practice TDD

- Have a mentor to ask questions, resolve doubts

I resolved the second point working in my personal projects. And the third one, asking coworkers, using web forums, reading examples, more books, reviewing open source code project, and I still working in the above three points. But I guess not all software developer has the available time and will to improve their skills in the same way. I push for a “self-learn” software developer, but the reality is, not everyone has the time to take that way. And it is a way with risks: you are on your own, and if you don’t have a dedicated mentor, it’s difficult to learn all the topics you need to cover in order to be proficient in TDD or in another best practice.

I’m working with Hogwarts Project team, to resolve such points: give people the support to learn TDD, IoC, SOLID principles, and more. Not only example, but rationale. Not only theory, but practice. Not only practice, but evaluation and post-support. In our case, the end customer bought the best practices idea: we have not needed to convince management of the advantages of best practices. We are in the early stage of the project: first deliverables are beta ones, and only internally distributed. But I hope that when the project gains more moment, more material and gained experience will be published and shared with the community.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

January 19, 2010

Tales from the Scrum: Is Agile/Scrum Hard?

Filed under: Agile Software Devevelopment, Scrum, Software Development — ajlopez @ 10:02 am

Recently, via some messages at Twitter, I found the post Agile/Pervagile on Slashdot in the multi-author blog Agile Advice – Working With Agile Methods (Scrum, OpenAgile, Lean). It’s an interesting reading, presenting Pervagile, the Perverted Agile. Most companies claims that they are using Agile, with Scrum or something alike, but, really, their adoption is partial. The author mention other deviations: Scrumbutt, Waterscrum, Scrummerfall, that deserve more comments here.

But today, I want to comment about the paragraph:

Agile is Hard

Okay, I’m actually being a little dis-honest.  The real truth is that doing agile is extremely, exceptionally, agonizingly difficult (for most people in most  organizations).  Why?  Because agile is not just another process to roll out.  It is, as has been mentioned in numerous places, a deep cultural change.  Agile is actually a liberation movement for people involved in software development.  Like most movements, however, it has been subject to corruptive forces.

Yes, true, but… I want to moderate above assertions, in the context of Scrum application (not Agile in general). If you are involved to introduce Scrum first time in your company, you need a cultural change, but I guess it could be not so deep. You need a proactive group of team members, a good ScrumMaster and Product Owner. AND (a no small and) the support from the management, to protect the team of outer interference, AND SPECIALLY the support of the Product Owner (protect him/her from other managers pressures, political forces, that could alter the priorities in product backlog, or that could interfere in the middle of the Sprint). The rest of your company can run in the old regime. But you need that your first project be protected. It needs nurturing and protection. Not a deep cultural change. The change in the rest of the company could be progressive. And the change in the team (I guess this is the first encounter of the members with Scrum) should be progressive, helped by an experienced ScrumMaster.

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

Older Posts »

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.