Category: Agile Practices

Two Things You Don’t Know About Unit Testing – Pt. 1

NUnit GUI, running unit tests for AutoWikiBrowser

Image via Wikipedia

 

Unit Tests Test Your Requirements, Not Your Code

When people are first getting started with writing unit tests, the pattern typically looks like this:

  1. Write classes and methods
  2. Write unit tests that test those classes and methods

Let’s say I was building an e-commerce application, and I had a ShoppingCart class with an AddProduct(IProduct product) method.  If I’m new to unit testing, I’m probably cutting my teeth by creating a ShoppingCartTest class that has an AddProductTest() method in it.  Lots of people start learning like this.  It is such a common way to do unit tests that certain testing frameworks will even take your code and automatically generate unit tests for you (MSTest, I’m looking in your direction).

Now, we all have to start somewhere, and this is also how I started writing tests, but the weakness of learning this way is, when you decide to make the shift into TDD by writing your unit tests first, most people are totally clueless as to how to do this.  How do you write unit tests before your code if the unit tests are strictly based around the code you’ve written?  These poor souls sweat railroad ties desperately trying to essentially write classes in their head, then write their tests, then write the classes.  This is TDD to them, and it is a painful and unhelpful thing.

The remedy to this, and the quickest path to becoming a TDD developer, is to learn to write unit tests that test your requirements.  This bears repeating with more whitespace around it.

Write tests that test your requirements.

There are all kinds of helpful testing frameworks to make this more intuitive (SpecFlow, MSpec, and many other excellent tools), but for the moment, I just want to focus on how to do this regardless of a specific tool.

To return to the e-commerce example above, let’s say I have the following requirement / user story / common sense insight that reads thus:

As a shopper, I want to add products to a shopping cart so that I can purchase them all at once.

Instead of sitting down and slamming out code for this or circling the nouns to get my class names, I’m going to write a test for this requirement.  Maybe it looks like this:

public class When_adding_a_product_to_the_shopping_cart
{
  public void The_number_of_items_in_the_cart_should_increase_by_one()
  {
  }
}

I would continue to add test methods for each thing that was supposed to be the case when someone added a product to the shopping cart.  For example, I might have a The_item_added_should_be_a_product method and so on.  Notice that the tests are being formed to test the requirement, not any specific code that might get the job done.  Notice that the class and method names read in a pretty straightforward manner.  This is how I know I’m covering my bases.  Even a business user could walk through this (with me, of course) and let me know if there were any aspects of adding a product that I was missing or misunderstanding.

So, now I start thinking about how to test that requirement.  Maybe it looks like this:

public class When_adding_a_product_to_the_shopping_cart
{
  public void The_number_of_items_in_the_cart_should_increase_by_one()
  {
    var cart = new ShoppingCart();
    var product = new Product();
    cart.AddProduct(product);
    Assert.IsTrue(cart.Products.Count == 1);
  }
}

Ok, that’s not actually the code I’d write, to be honest.  The product should be a mock.  I’d set up the cart and possibly execute the add in a precondition to this test and just check the product count in the actual test method, but I don’t want to muddy the waters right now.

This test code will break, of course, mostly because I made reference to a ton of things that don’t exist in my code.  The test will be red.  It now becomes my responsibility to write the smallest amount of code I can that will make this test compile and run successfully.

There are two, huge benefits (among others) from writing your tests this way (which is more of a BDD way):

One, writing your tests first becomes a lot easier.  You write classes around the basic pieces of required functionality and methods around the stuff that should happen with that functionality.  Your methods should also include what happens when things go wrong, etc.  Basically the kind of stuff you need to know to build your application.  Once I have that broken down, it’s a lot easier to formulate the kind of code I’d need to get that done.

Two, and this cannot be stated enough, successful tests mean that I’m delivering what the application should do, not that my code does what I expect.  We’ve all seen it – a nice suite of unit tests that run green, but the code doesn’t deliver on the expected requirements.  It works, it does what you told it to do, it just doesn’t do what anybody wanted or needed.  In this methodology, if all my tests pass, it means my code is fulfilling the functionality we needed, not simply that the code is working as intended.

You can probably see where this is going.  In Part 2, we’ll look at how this process helps you write actual code.

Did you like this? Share it:

Vendor or Partner–You Decide

Confused Chimp

There are roughly 3 models of consulting being practiced in the Kansas City market.  Two of these 3 models are vendor-based models and 1 is a partnership-based model which I will explain below. A vendor-based model is one that looks very similar to a relationship someone may have with their plumber, mechanic, or cleaning people.  This model doesn’t value relationship nearly as much as it values the façade of control and value.  The first 2 I will be talking about follow the vendor-based pattern that is popular and well-known in our community today.

Vendor-Based Staffing Model

These types of firm typically came from a staffing agency.  Dealing with these agencies can oftentimes be as challenging as placing an ad in CareerBuilder.  Clients tend to have to sift through countless firms before they find one that shows the ability to deliver quality talent honestly and with integrity.  This model was formed for a couple of different reasons.  The primary being as a result of market forces that made placing people difficult.  The other reason was more simple…they had resumes and they had companies needing bodies, so why not?

A staffing agency’s competitive advantage comes from their ability to compete on price.  Secondary to the bottom dollar, comes value and continuity for the client.  Their resources are not committed to their firm nor to the client and turnover is extremely high.  Value is the other concern in working with these vendors as the resources are extremely hit-or-miss with missing occurring far to often.  These firms have an inability to know what to look for as far as talent and background as referenced by the many times I have been contacted by staffing firms asking me what a skill was so they could talk halfway intelligently about it.

Relationships with these companies, while something of a gamble, work for some clients as they may get a hit on a valued resource or have the staff to sift out the talented from those lacking.  More often than not, I have found many companies in our area disillusioned by staffing firms playing at professional consulting firms and do not recommend this model for anyone.

Vendor-Based “Name Brand” Model

These types of firms rely almost solely on the “wow” factor for their success.  I say “almost” only so far as many of these companies also rely on their reputation from past successes.  The best advice I can give on this point is past successes are NOT always indicators of future success.

A branded models’ competitive advantage comes from the ability to “wow” the client with large and very formal presentations.  While these flashy performances and personalities speak well for a company, I’ve found these people tend to disappear shortly after the project is in full swing and are replaced by the same low-end talent often found in the staffing pool spoken about above.  These companies tend to rely on patterns and practices drilled into the heads of their consultants to bring a project to success.

Furthermore, the projects tend to run hidden in a veil of paperwork and process and are extremely fat on bureaucratic inefficiencies.  Presence is everything to these companies but always bear in mind, success is measured by the margins on every project they become involved in.  These companies will do whatever is necessary to protect those margins and keep them in a range that keeps them gainfully employed thereby firmly establishing them in the “vendor-based” space they live in.

The Partner-Based Model

A partner-based model is just like what its name infers.  It has focus on relationships and value first, with literally everything else secondary to that.  At the core of this approach is education and building trust upfront.  This has become a necessity as most potential clients have had negative experiences with a consulting firm at some time in their past.  Since this is the approach that AdventureTech takes, let’s take a closer look at how we implement this model.

AdventureTech’s Partner-Based Model

AdventureTech was built by seeing the failed traditional models spoken about above and molding a model that better fit the personalities and traits that make up a successful software development company in the Midwest market. Our model tends to focus on an extremely open process and working in the organization as opposed to for the organization. In every project that AdventureTech is involved, our clients have intimate knowledge of the details. Now the pros of this are apparent…clients know what they’re getting, when they’re getting it, and all the inner workings of the project.  The cons are some clients do not want all of that as they do not think they can provide enough value to make that worthwhile.  We come alongside our clients to show them the truth that a project simply will not be as successful as it could or should be minus a business’ direct involvement as partners on the team.

AdventureTech sets itself apart from the staffing model by employing well-known talent in the market as full-time employees.  Our primary competitive advantage comes from our knowledge and understanding that our greatest asset is our employees.

In addition to that, we shy away from the “name brand” model mentioned above simply because that is not who we are.  First of all, we aren’t nearly as good looking as those guys and girls but second of all, we are developers through and through.  From the top level management to the lowest level employee, we roll up our sleeves and get right into the heart of our clients businesses.  There is no one in our organization too proud or too far removed from the technology that they can’t sit down and begin coding today and many are actively doing so.  Therefore, we remove the flashy and somewhat shallow presentations with rich education that our clients can comprehend and base sound business and technical decisions on.

The competitive advantage that is so unique to our partner-based model comes from the quality of our people, an open process, and a willingness to come alongside our clients as a part of their organization.  Having a relationship with AdventureTech means not just the investment of capital in a project but investing your organization’s time and energy in the software development process.  This is something most companies have little to no experience being involved in, but is an essential ingredient to the success of all of our endeavors.  It is challenging to develop software, but rather than trying to hide this challenge in hard to understand technical bureaucracy and process, AdventureTech puts our clients on the team to build software as efficiently and effectively as possible.

Did you like this? Share it:

Fake It Easy On Yourself

I have been using Rhino.Mocks pretty much since I started being a mockist-type tester. I have been very happy with it for the most part, but a year or so ago, I got a glimpse of some tests using Moq. I thought the little bit I saw was very compelling. For a long time, I had been using:

   1: var _repository = MockRepository.GenerateMock<IRepository>();

   2: _repository.Expect(repo=>repo.SomeCall()).Return(SomeValue);

   3: var _controller = new SomeKindaController(_repository);

   4:  

   5: ... some exercising code

   6: _repository.AssertWasCalled(repo => repo.SomeCall());

 

I was happy with that syntax. I didn’t go looking for something else, but what I saw was:

   1: var _repository = new Mock();

 

And I thought, “That looks really nice!” The code was very expressive and easier to read that the Rhino.Mocks syntax. I have gotten so used to the Rhino.Mocks syntax that it made complete sense to me, but to developers I was mentoring in mocking, it was sometimes to obtuse.

SO I thought I would write some tests using Moq as my mocking tool. But I discovered something ugly once I got into it. The way Mocks are created makes Moq very easy to read, but that only gives you a Mock not the object itself, which is what you’ll need to pass to the exercising code. So this is what it ends up looking like:

   1: var _repository = new Mock<IRepository>();

   2: _repository.SetUp(repo=>repo.SomeCall).Returns(SomeValue);

   3: var _controller = new SomeKindaController(_repository.Object);

   4: .. some exercizing code

   5: _repository.Verify(repo => repo.SomeCall());

 

Two things jump out at me: 1) when I set up my mocked calls, do I set it on the Mock or the Mock’s “object”? and 2) What am I verifying on SomeCall? Just that it was called? that it is available to call? Dealing with 2 objects, a “Mock” and an “Object” made me have to consider naming conventions. Should I always call the mock _repositoryMock and the object _repository? So I went back to Rhino.Mocks. It is the most widely used framework, and show other how to use it is easier because there is one natural object to use, the _repository.

Then I came across a blog post from Patrik Hägne, and that led me to a post about FakeItEasy. I went to the Google Code site and when I saw the syntax, I got very excited. Then I read the wiki page where Patrik stated why he wrote FakeItEasy, and it mirrored my own experience. So I began to play with it a bit. So far, I am sold. the syntax is VERY easy to read and the fluent interface is super discoverable. It basically looks like this:

   1: var _repository = A.Fake<IRepository>();

   2: a.CallTo(repo=>repo.SomeMethod()).Returns(SomeValue);

   3: var _controller = new SomeKindaController(_repository);

   4: ... some exercising code

   5: A.CallTo(() => _repository.SOmeMethod()).MustHaveHappened();

 

Very nice. But is it mature? It’s only been around a couple of years, so will I be giving up some thing that I use a lot because it hasn’t been implemented yet? I doesn’t seem so. As I read more examples and posts from Patrik, he has some pretty complex scenarios. He even has support for VB.NET!

So if you are looking for a mocking framework that looks and feels very natural, try out FakeItEasy!

 
Did you like this? Share it:

Connect With Us

     

Contact Us

Toll Free: (888) 373-8718
Main: (913) 402-9600
Fax: (913) 402-9603
7450 W. 130th Street
Suite 320
Overland Park, KS 66213

Upcoming events

  • Events on June 18, 2013

    Kanban Training

    Starts: June 18, 2013, 12:00 am

    Ends: June 20, 2013, 12:00 am

  • Events on June 20, 2013

    LWS Lunch

    Starts: June 20, 2013, 11:30 am

    Ends: June 20, 2013, 1:00 pm

    Location: DEG Offices

  • Events on July 18, 2013

    LWS Lunch

    Starts: July 18, 2013, 11:30 am

    Ends: July 18, 2013, 1:00 pm

    Location: DEG Offices

  • Events on August 15, 2013

    LWS Lunch

    Starts: August 15, 2013, 11:30 am

    Ends: August 15, 2013, 1:00 pm

    Location: DEG Offices

  • Events on September 19, 2013

    LWS Lunch

    Starts: September 19, 2013, 11:30 am

    Ends: September 19, 2013, 1:00 pm

    Location: DEG Offices

  • Events on October 17, 2013

    LWS Lunch

    Starts: October 17, 2013, 11:30 am

    Ends: October 17, 2013, 1:00 pm

    Location: DEG Offices

  • Events on November 21, 2013

    LWS Lunch

    Starts: November 21, 2013, 11:30 am

    Ends: November 21, 2013, 1:00 pm

    Location: DEG Offices

  • Events on December 19, 2013

    LWS Lunch

    Starts: December 19, 2013, 11:30 am

    Ends: December 19, 2013, 1:00 pm

    Location: DEG Offices

  • Events on January 16, 2014

    LWS Lunch

    Starts: January 16, 2014, 11:30 am

    Ends: January 16, 2014, 1:00 pm

    Location: DEG Offices

  • Events on February 20, 2014

    LWS Lunch

    Starts: February 20, 2014, 11:30 am

    Ends: February 20, 2014, 1:00 pm

    Location: DEG Offices

  • Events on March 20, 2014

    LWS Lunch

    Starts: March 20, 2014, 11:30 am

    Ends: March 20, 2014, 1:00 pm

    Location: DEG Offices

  • Events on April 17, 2014

    LWS Lunch

    Starts: April 17, 2014, 11:30 am

    Ends: April 17, 2014, 1:00 pm

    Location: DEG Offices

  • Events on May 15, 2014

    LWS Lunch

    Starts: May 15, 2014, 11:30 am

    Ends: May 15, 2014, 1:00 pm

    Location: DEG Offices

  • Events on June 19, 2014

    LWS Lunch

    Starts: June 19, 2014, 11:30 am

    Ends: June 19, 2014, 1:00 pm

    Location: DEG Offices

Recent tweets