TheHumbleProgrammer

Just another WordPress.com weblog

Keep on tweaking – solution

Posted by thehumbleprogrammer on July 10, 2009

in my previous post I published the following code

   1: public void SetCustomerPropertiesOnView(IEnumerable<Customer> customers)
   2: {
   3:     int count = 1;
   4:     string previousSurname = string.Empty;
   5:     foreach (var customer in customers)
   6:     {
   7:         this.View.AllCustomers.Add(new CustomerDisplay(customer));
   8:  
   9:         if (count == 1)
  10:             previousSurname = customer.Surname;
  11:  
  12:         if (customer.Surname != previousSurname)
  13:         {
  14:             this.View.SurnameFilter.Add(new NorthWindListItem(customer.Surname, customer.ID.ToString()));
  15:             previousSurname = customer.Surname;
  16:         }
  17:         count++;
  18:     }
  19: }

The context around this code is a view that shows all customers and allows the user to filter on surnames. Therefore I go and get the customers from the database I transform them for display and extract the unique surnames for the filtering functionality. I want to do all of this in one iteration of the customer list.

The above code achieves this aim, it may well be a naive implementation and there are other ways of doing this in a more efficient manner. That said the point of this post is to focus on the maintainability of this implementation, not it’s efficiency or approach. I would say that most developers would probably leave this implementation as is once they have achieved the goal. They would probably not be inclined to refactor this working solution into a more elegant solution that is maintainable over time.

My end solution to this problem looks like this

   1: public void SetCustomerPropertiesOnView(IEnumerable<Customer> customers)
   2: {
   3:     var customersAndSurnames = customers.TransformForDisplay().AndGetDistinctSurnames();
   4:  
   5:     this.View.AllCustomers = this.GetCustomersFrom(customersAndSurnames);
   6:     this.View.Surnames = this.GetUniqueSurnamesFrom(customersAndSurnames);
   7: }

The implementation of the two extension methods is not really that important in the end we still have the horrible implementation, but at the top level when the next guy comes along to add or maintain this code they will have some context around what we are trying to do. SetCustomerPropertiesOnView now has a more declarative style, you can see straight away that we are transforming customers for display and getting distinct surnames in order to give them to the view. The two private methods are just wrappers around extraction of the values in a C# implementation of a tuple, which is used to return two different types of values from one method without using out or ref parameters.

In conclusion once you have found a solution that works don’t just stop there, use the tests too aid your refactoring of a first attempt into a more maintainable elegant intention revealing block of code.

Posted in Uncategorized | Leave a Comment »

Keep On Tweaking

Posted by thehumbleprogrammer on July 3, 2009

What does this piece of code do?

   1: public void SetCustomerPropertiesOnView(IEnumerable<Customer> customers)
   2: {
   3:     int count = 1;
   4:     var previousSurname = string.Empty;
   5:     foreach (var customer in customers)
   6:     {
   7:         this.View.AllCustomers.Add(new CustomerDisplay(customer));
   8:  
   9:         if (count == 1)
  10:             previousSurname = customer.Surname;
  11:  
  12:         if (customer.Surname != previousSurname)
  13:         {
  14:             this.View.SurnameFilter.Add(new NorthWindListItem(customer.Surname, customer.ID.ToString()));
  15:             previousSurname = customer.Surname;
  16:         }
  17:         count++;
  18:     }
  19: }

 

I will explain the reasons behind this code, and come up with a more refined solution in a later post. More often than not we come across implementations like this where the maintainer has to work really hard to get to the intent of the code.  In short this is an example of working code that is not easily maintainable over time, we can and should do better. With the safety net of unit tests I can now play around with this code to make it better.

This all goes back to Mike Waggs post on why he loves TDD/BDD particularly when he talks about tweaking code

“The best developers are those that continuously refine their code. They take something that is just a solution to the problem at hand and transform it into something which is clean and elegant. They craft a piece of code that is easily understandable by other developers and which can be easily maintained as the requirements of the system changes.”

I couldn’t agree more with this sentiment. The code above is a practical example of why we should strive to keep on tweaking. As I said before the code works, it does a job, should I walk away happy with this implementation. Absolutely not, we can make it better, so that the next person that has to delve into this code will get more understanding from reading it, not more questions.

Trying to understand this implementation will take time, to the business time is money and developer time is even more money. So for the good of the business don’t lock in your ignorance by leaving a first attempt at a solution to a problem, tweak it, until it clearly expresses your intent.

My solution will follow…what’s yours?

Posted in Agile, Quality | 1 Comment »

Given you’ve heard of BDD, When you try to get started, Then you will find much confusion and anger.

Posted by thehumbleprogrammer on April 18, 2009

On my last project, as part of a developer wide shift I was introduced to Behaviour Driven Development. BDD has been gathering interest in the test driven community for quite some time. For a good background to this development technique it’s best to start at the beginning and  read Dan North’s article introducing BDD. From this article you can see the intention of BDD is to simplify a test first approach to software development,

I had a problem. While using and teaching agile practices like test-driven development (TDD) on projects in different environments, I kept coming across the same confusion and misunderstandings. Programmers wanted to know where to start, what to test and what not to test, how much to test in one go, what to call their tests, and how to understand why a test fails.

The deeper I got into TDD, the more I felt that my own journey had been less of a wax-on, wax-off process of gradual mastery than a series of blind alleys. I remember thinking “If only someone had told me that!” far more often than I thought “Wow, a door has opened.” I decided it must be possible to present TDD in a way that gets straight to the good stuff and avoids all the pitfalls.

My response is behaviour-driven development (BDD). It has evolved out of established agile practices and is designed to make them more accessible and effective for teams new to agile software delivery. Over time, BDD has grown to encompass the wider picture of agile analysis and automated acceptance testing.

thus lowering the entry level, which will increase take up amongst developers and the quality bar will be increased. Once you have read the article and, like me, felt an overwhelming desire to make the jump from boring old TDD to brand new BDD immediately, you will then mistakenly Google a phrase such as “Getting Started With BDD“. Ignoring the Microsoft articles you will avidly read anything and everything in this search result trying to grok BDD, unfortunately all you will find my friend, is confusion and anger.

In the end you must resist the urge to download any of the BDD frameworks out there until you have gotten your hands dirty writing your own implementation of BDD. Once you have become comfortable with this, by all means move onto a framework that allows you to bake the user stories into the tests rendering them unreadable at a glance etc. It’s your choice, we live in a democracy.

Getting started with BDD the pain free way.

first go to Ben Scheirman’s excellent article outlining the Transition from TDD to BDD, this will give you a clear grounding in making the move. Then have a play around with subclassing Ben’s base class and implementing some BDD test fixtures. Tim and Mike did this in my last company resulting in a nice simple framework that could be rolled out across the developer team with a minimal learning curve. The minimal learning curve is very important if you want take up of BDD, which is what the framework writers have forgotten in trying to cleverly bake trace ability from stories too behaviour into the test suite.

An example of our version of BDD would look like this:

   1: namespace specs_for_SessionManager
   2: {
   3:     public abstract class SessionManager_base_context : Specification<SessionManager>
   4:     {
   5:         protected Mock<ISession> Session { get; private set; }
   6:         protected String SessionName { get; private set; }
   7: 
   8:         protected override void EstablishContext()
   9:         {
  10:             Session = base.Substitute<ISession>();
  11:             Session.Setup(s => s.Close());
  12:             Session.Setup(s => s.BeginTransaction()).Returns(base.Substitute<ITransaction>().Object);
  13:         }
  14: 
  15:         protected override SessionManager CreateSubject()
  16:         {
  17:             return new SessionManager(Session.Object, SessionName);
  18:         }
  19:     }

Here I have my specifications for the SessionManager, I then subclass Bens base class and override the necessary methods to establish a context and create the system under test. I can then go on to create a scenario for different behaviours of the system.

   1: [TestFixture]
   2: public class when_closing_a_session : SessionManager_base_context
   3: {
   4:     protected override void When()
   5:     {
   6:         base.Subject.CloseSession();
   7:     }
   8: 
   9:     [Test]
  10:     public void underlying_session_should_be_called()
  11:     {
  12:         Session.AssertWasCalled(s => s.Close());
  13:     }
  14: }
  15: 
  16: [TestFixture]
  17: public class when_beginning_a_transaction : SessionManager_base_context
  18: {
  19:     protected override void When()
  20:     {
  21:         base.Subject.BeginTransaction();
  22:     }
  23: 
  24:     [Test]
  25:     public void a_transaction_should_have_begun_on_the_underlying_session()
  26:     {
  27:         Session.AssertWasCalled(s => s.BeginTransaction());
  28:     }
  29: }

As you can see we have a test fixture for each scenario, which overrides the when method in order to invoke the system under test in this context. Each test makes some assertion for expected behaviour in this scenario. Note the tests are now just one line assertions, we have split out the arrange and act part of the tests into the base class and the When method. The outcome of all this is a nice report in your resharper test runner like so;

NotQuiteRight_BDD

This is a big step in the right direction, we can see the scenario that we are testing and the outcome of that behaviour being invoked, the only thing we are missing is the given. With the current style I found myself tacking on some context to the class name like so

when_beginning_a_transaction_with_a_pre_existing_transaction

This is not quite right, in my code I want to say Given a transaction is running When beginning a transaction Then an exception should be thrown, I can’t easily do that with the current structure so I tried using the namespace for the given and now my structure looks like this:

   1: 
   2: namespace base_context_for
   3: {
   4:     public abstract class session_manager : Specification<SessionManager>
   5:     {
   6:         protected Mock<ISession> Session { get; private set; }
   7:         protected Mock<ITransaction> Transaction { get; private set; }
   8:         protected String SessionName { get; private set; }
   9: 
  10:         protected override void EstablishContext()
  11:         {
  12:             Session = base.Substitute<ISession>();
  13:             Transaction = base.Substitute<ITransaction>();
  14:             Session.Setup(s => s.Close());
  15:             Session.Setup(s => s.BeginTransaction()).Returns(Transaction.Object);
  16:         }
  17: 
  18:         protected override SessionManager CreateSubject()
  19:         {
  20:             return new SessionManager(Session.Object, SessionName);
  21:         }
  22:     }
  23: }
  24: 
  25: namespace given_a_session_is_open
  26: {
  27:     [TestFixture]
  28:     public class when_closing_a_session : base_context_for.session_manager
  29:     {
  30:         protected override void When()
  31:         {
  32:             base.Subject.CloseSession();
  33:         }
  34: 
  35:         [Test]
  36:         public void underlying_session_should_be_closed()
  37:         {
  38:             Session.AssertWasCalled(s => s.Close());
  39:         }
  40:     }
  41: }

As you can see my base context is now in its own namespace called base_context_for, the base context class name is just the system under test. I can then subclass the base class with a fully qualified name, like so;

public class when_closing_a_session : base_context_for.session_manager

The above signature makes it really easy to see exactly what the system under test is and what the scenario is. 

On line 25 you will see that I have another namespace declaration to wrap the subclass, the namespace becomes the given, the class name is the when and the test methods correspond to then. Giving a nice resharper report like this:

final_bdd

For those of us that like to run TestDriven.Net, we will still get the same output when all is good

5 passed, 0 failed, 0 skipped, took 2.33 seconds.

but if you get a failing test you get the following output:

TestCase ‘given_a_transaction_already_exists.when_beginning_a_transaction.should_throw_invalid_operation_exception’

failed:
  Expected: instance of <System.InvalidOperationException>
  But was:  null

you can clearly see on the top line a full scenario description, which should make it nice and easy to figure out exactly what the issue is.

Conclusion

It is still early days for me and BDD but I am enjoying it and can see the benefit. For me BDD is all about giving an intuitive entry point into test first development, a by product of this is a nice report that developers can quickly see what is going wrong in their system under certain conditions. I think that trying to bake the full user story into the system at all levels of testing is a recipe for disaster. The frameworks for BDD seem to be geared towards the being able to trace a user story to some behaviour in your system. This leads to confusion for the developer, long overly noisy tests peppered with unmaintainable strings. The transition is now complete from TDD to BDD, until I have more experience in writing Behaviour fixtures I will stick to this structure. I would love to hear any of your thoughts (not you mum, my other reader, cheers big bro) on this structure and how it can be improved.

Posted in BDD, Unit testing | 5 Comments »

Leap of faith

Posted by thehumbleprogrammer on December 16, 2008

Over the past couple of months I have taken the plunge and decided to go into the murky world of short term contracting (hence why the blog has been so quiet of late). With my current experience most companies want me to move up the ladder to senior dev roles. Whilst I feel that this is ultimately a good thing I feel that I need to learn a hell of a lot more about software development before I can begin to lead a team and mentor junior devs on the job. Moving up the ladder, being in a position of influence is something that I take very seriously. I feel that too many companies/devs are too eager to move up the ladder without having gained enough real experience with different projects in different problem domains.

I have been really spoilt by my first contract as the client I am working with does a lot of the Agile practices I have been looking for. The upper management believe and back these Agile practices such as close customer contact, TDD and continuous integration. In general the output from this team of developers is very stable with few issues coming back once released. Working for this client has convinced me more than ever that good Agile practices are the way to go when authoring Business software.

More on this later…for now I got work to do…

Posted in Agile, Working practices | Leave a Comment »

Mock Object Frameworks Part 3

Posted by thehumbleprogrammer on September 23, 2008

In part 1 of this series I introduced the idea of substituting collaborating objects with test doubles in order to unit test your classes in isolation. In part 2 I then went on to introduce reasons to choose Rhino Mocks and the four types of test doubles rhino mocks gives you in order to carry out state or interaction based unit testing. In this article I am hoping to introduce testing events as well as some of the more common gotchas that catch out beginner users of Rhino mocks.

Understanding Error Messages

For beginner users of the Rhino mocks framework the biggest issue can be in trying to understand the error messages that are returned when an exception is thrown.

[Test]
public void Should_Call_GetById_When_Handling_The_View_Load_Event()
{
   this.Setup();
   IService<Customer> serviceMock = repository.StrictMock<IService<Customer>>();
   Expect.Call(serviceMock.GetById(4)).Return(this.customer);
   this.repository.ReplayAll();

   CustomerPresenter presenter = new CustomerPresenter(serviceMock, this.customerViewDMock);
   presenter.HandlePageLoad();
   this.repository.VerifyAll();
}

In the test method above I am creating a strict mock on line 3, I then set an expectation that the GetById() will be called and when it is, return the customer instance created earlier in the Setup(). The call to ReplayAll() on the repository lets the framework know that the record phase is complete and we are ready to playback any expectations during the execution of the unit under test. I then create the presenter instance and call the unit under test, which in this case is HandlePageLoad(). Finally I call VerifyAll() on the repository to assert that the expectations set earlier have been met.

When run the test fails with the following message;

Rhino.Mocks.Exceptions.ExpectationViolationException: IService`1.GetById(4); Expected #1, Actual #0.

As you can see an ExpectationViolationException has been thrown. The error message that we are interested in begins after the colon, it’s telling us that a call to IService.GetById(4) was expected once but actually called zero times. In this case I am doing an Interaction based test to ensure that GetById() on the service is called, because I have not implemented the HandlePageLoad() method on the presenter the expectation set in the record phase has not been met during the replay, resulting in the above exception. To fix this I add the following to the HandlePageLoad() method.

public void HandlePageLoad()
{
    Customer toDisplay = this.Service.GetById(4);
}

As you can see I have implemented just enough to get the test to pass, I have hard coded in the customer id in the call to GetById(4). In reality the customer id will be retrieved from the View.CustomerId property. I change the implementation to make the call to the view like so;

Customer toDisplay = this.Service.GetById(this.View.CustomerId);

Now I get the following error message.

Rhino.Mocks.Exceptions.ExpectationViolationException: IService`1.GetById<System.Int32>(0); Expected #0, Actual #1.
IService`1.GetById<System.Int32>(4); Expected #1, Actual #0.

Because I am using a strict mock the framework finds two expectation violations.

  • GetById<System.Int32>(0); Expected #0, Actual #1 – is caused by the call to GetById() in the HandlePageLoad() implementation, because I am now getting the customer id from the view and I have not setup any value for it to return (the view is a strict mock controlled by the framework) customerid will always return the default value, in this case 0. The expectation violation is caused by the GetById(0) being called in the implementation and not having an Expect.Call(… etc set for it in the record phase of the unit test.
  • GetById<System.Int32>(4); Expected #1, Actual #0 – is caused by the Expectation not being met for a call to the GetById(4) method with a parameter value of 4. We explicitly set this expectation in the unit test before the call to ReplayAll().

In short this whole issue is being caused by the parameter value being used in setting the expectation, I am using the hard coded value 4 in the expected call to GetById() but in the implementation GetById() is being called with the default customer id, which in this case is 0. We can remedy this situation by using IgnoreArguments like this;

Expect.Call(serviceDMock.GetById(4)).IgnoreArguments().Return(this.customer);

Adding a call to IgnoreArguments tells the framework to ignore any values passed into the call to GetById during the execution of the method under test. Now my test is more robust because it will fail when the GetById is not called but if the customer id property changes on the view it will have no effect on the test.

By carefully looking at the error message above we can see that the first part says that a call to IService.GetById(0) was not expected but called anyway and a call to IService.GetById(4) was expected but not met. With value types the clue is in the error message we can see the 0 and the 4 are the parameters making it that bit easier to figure out what is going on. When using reference types we get an even more cryptic error message, by changing the GetById so that it takes a Customer object setting the expectation looks like this;

Expect.Call(serviceMock.GetById(new Customer())).Return(this.customer);

and the new implementation looks like this;

//this is a simple implementation for demo purposes only
Customer toDisplay = this.Service.GetById(new Customer());

and when run the error message looks like this;

Rhino.Mocks.Exceptions.ExpectationViolationException: IService`1.GetById(Rhino.CommonGotchas.Customer); Expected #0, Actual #1.
IService`1.GetById(Rhino.CommonGotchas.Customer); Expected #1, Actual #0.

The parameter being passed in to the GetById(Customer) is the problem. When I set the expectation in the record phase of the unit test I passed in a new Customer and when I implemented the HandlePageLoad() method I also passed  in a new Customer in the call to GetById. The framework is using reference equals to check that the parameter being passed in the expectation is the same as the parameter being used in the actual implementation. In this case they are not, so we get the message GetById(Customer) wasn’t expected but actually called, GetById(Customer) was expected but never called. Again IgnoreArguments sorts this out but the error message is very confusing.

More Flexibility Using Dynamic Mocks

I get the two tier error message above because I am using strict mocks and as we all know from part 2 strict mocks will fail a test when either all expected calls have not been met or if unexpected calls are made on the mocked object during the execution of the unit under test. If however we use a dynamic mock in the above example we will only get the one error message. The framework will ignore the fact that a call has been made with the incorrect parameter and will fail on the fact that the expectation has not been met. The expectation has not been met because we have made an explicit expectation that a call to the GetById(param) will be called, we have not let the framework know that the parameters are not important so it will fail the verification. Once I tell the framework to ignore parameters the test will pass.

As a side note this is another reason why I am moving towards using dynamic mocks as apposed to strict mocks. They allow you to write more flexible interaction based tests that will fail for the right reason. So in the example above If someone refactors the implementation in such a way that the call to GetById(int) does not happen then the test will fail, the developer will see a failing test named Should_Call_GetById_When_Handling_The_View_Load_Event() and they can then decide whether in light of the refactoring this is a valid test or not.

Don’t Forget ReplayAll()

Not calling replay all on a series of expectations or when setting up results on stubs can cause many side effects, ranging from null pointer exceptions in the best case to an incorrectly passing test in the worst case. The most common time to be caught out by this scenario is when you are stubbing out a collaborator and you just want a quick one line way of setting up a result when the stub is called. The example in this section is for saving a customer that has been updated on the view to the database. The (contrived ;-))  implementation  of the save method is as follows;

public void Save()
{
    Customer customer = this.View.GetCustomer();
    string phoneNumber = customer.Telephone;
    //do some validation on the phone number....
    this.Service.Save(customer);
}

I am getting the updated customer from the view, then getting the telephone number from the returned customer and validating that it meets some criteria finally I am saving it to the database. In my first test for this I want to ensure that only valid phone numbers are being saved to the database, so I stub the view and the service in order to assert state, like so;

[Test]
public void Should_Validate_PhoneNumber_Before_Saving()
{
    this.Setup();
    Service<Customer> serviceStub = repository.Stub<Service<Customer>>();
    ICustomerView viewStub = this.repository.Stub<ICustomerView>(); 

    Customer customerToSave = GetCustomerToSave(); 

    SetupResult.For(viewStub.GetCustomer()).Return(customerToSave);
    serviceStub.Save(new Customer());//Tell the framework a call to save, which is a void method will be made
    LastCall.Callback(new Delegates.Function<bool, Customer>(this.AssertPhoneNumberIsValid)); //Set a callback on the call to save so that I can assert on the phone number 

    CustomerPresenter presenter = new CustomerPresenter(serviceStub, viewStub);
    presenter.Save();
}

I then setup a result on the GetCustomer() method  telling the framework to return the dummy customer when it is called during the execution of the unit under test. On the next line I set a call to a the void method Save(customer) on the service, following it by setting a callback method on the lastcall made by the repository. This callback method will contain all of the assertions on the phone number to ensure that only valid customers are sent to the database. When I run this test I get a null pointer exception in the second line of the Save() method on the presenter. In this line I am trying to retrieve the telephone number from the customer returned from the view, but the view’s GetCustomer() is returning null. I have set a result on the call to GetCustomer() to return a customer instance so I should not be getting a null pointer. The reason behind this is because I have forgotten to call Repository.ReplayAll() to set the repository into the replay phase. Once I put in the missing line the test works as expected, the test now looks like this;

[Test]
public void Should_Validate_PhoneNumber_Before_Saving()
{
    this.Setup();

    Customer customerToSave = GetCustomerToSave();

    ...
    this.repository.ReplayAll();

    CustomerPresenter presenter = new CustomerPresenter(this.serviceStub, viewStub);
    presenter.Save();
}

As with all of these things I have options, first up I could use a using block with a call to Repository.Record() like this;

[Test]
public void Should_Validate_PhoneNumber_Before_Saving()
{
    this.Setup();
    Service<Customer> serviceStub = repository.Stub<Service<Customer>>();
    ICustomerView viewStub = this.repository.Stub<ICustomerView>();

    Customer customerToSave = GetCustomerToSave();

    using (this.repository.Record())
    {
        SetupResult.For(viewStub.GetCustomer()).Return(customerToSave);
        serviceStub.Save(new Customer());//Tell the framework a call to save, which is a void method will be made
        LastCall.Callback(new Delegates.Function<bool, Customer>(this.AssertPhoneNumberIsValid)); //Set a callback on the call to save so that I can assert on the phone number
    }

    CustomerPresenter presenter = new CustomerPresenter(serviceStub, viewStub);
    presenter.Save();
}

When the record block is exited a call to ReplayAll() is made behind the scenes in that way you don’t have to remember to call it explicitly. I feel that by using the block in this test increases the noise to code ratio making the code that little bit harder to understand. Also Record blocks are usually followed by PlayBack blocks that make the whole test easier to understand, as a rule of thumb I only use these blocks if I have 3 or more lines of expectations and Stubbed result setup in my tests. I feel that any less than that the using blocks cause too much noise for very little benefit. That is especially so in a state based test where you are purely stubbing out collaborators.

Setters and Stubs

Once you get passed the Record/Replay/Verify stuff and you have some understanding of the difference between Mocks/Stubs/Fakes/Dummies you will probably grow to enjoy using the framework to make your tests easier to write and maintain. As you get more accustomed to using the framework you will probably do as I did and forget that you don’t have to Setup Results on a stubbed object that has a read/write property, all you need to do is set the property on the stub and it will just work as expected. It seems obvious and it is obvious but you will probably forget about the setter and try to setup result like this;

the view interface

public interface ICustomerView
{
   int CustomerId { get; }
   Customer Customer { get; set; }
   void AttachDataSource(Customer dataSource);
   Customer GetCustomer();
}

As you can the Customer property is read/write the test method that stubs out the view is carrying on with the theme outlined above and looks like this;

[Test]
public void Should_Validate_PhoneNumber_Before_Saving()
{
   this.Setup();

   Customer customerToSave = GetCustomerToSave();

   SetupResult.For(this.viewStub.Customer).Return(customerToSave);
   serviceStub.Save(new Customer());//Tell the framework a call to save, which is a void method will be made
   LastCall.Callback(new Delegates.Function<bool, Customer>(this.AssertPhoneNumberIsValid)); //Set a callback on the call to save so that I can assert on the phone number
   this.repository.ReplayAll();

   CustomerPresenter presenter = new CustomerPresenter(this.serviceStub, viewStub);
   presenter.Save();
}

The third line of the test, in bold, sets up a result on the views’ customer property to return a dummy instance to save. It all looks very familiar, when I run this test I get the following error;

System.InvalidOperationException: Invalid call, the last call has been used or no call

has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).

As you can see from the test above I am calling a virtual method and a call has been made, I also don’t think knowing that the last call has been used really helps me in this scenario. The problem is being caused by me forgetting to set the Customer property directly on the Stubbed view like this;

[Test]
public void Should_Validate_PhoneNumber_Before_Saving()
{
   this.Setup();

   Customer customerToSave = GetCustomerToSave();

   this.viewStub.Customer = customerToSave;
   ...
}

Testing Events

There are two areas to testing events,

  1. Test that subscribers attach to events correctly
  2. Test that when thrown the event is handled

Thankfully rhino mocks gives us some mechanisms to carry out both types of tests. In my first test, again using the theme of a customer presenter instead of using direct calls from the view to the presenter I will be communicating through events. This first test is to ensure that when the presenter is constructed the Load event of the view is attached to. The test looks like this;

[Test]
public void Should_Attach_To_Page_Load_On_View()
{
    this.Setup();

    Expect.Call(() => this.customerViewDMock.Load += null ).IgnoreArguments();
    this.repository.ReplayAll();

    new CustomerPresenter(this.serviceStub, this.customerViewDMock);
    this.repository.VerifyAll();
}

As you can see it’s pretty straight forward, in the second line of the test I am setting up an expectation that something will attach to the Load event of the view. I then instruct the framework to IgnoreArguments on the expectation, in this case the null being attached to the Load event. You can also set constraints on the last call specifying things like Is.NotNull on anything attaching to the event. I then instantiate the presenter, which is the unit under test, and verify that all expectations have been met. In order to pass the test I implement the following constructor;

public CustomerPresenter(IService<Customer> service, ICustomerView view)
{
    this.Service = service;
    this.View = view;
    this.View.Load += ((sender, args) => Console.WriteLine("view loading"));
}

The next thing to test is handling the load event, the first test I want to do is an interaction based test to ensure that the GetById() method is called on the service. My test looks like this;

[Test]
public void Should_Call_GetById_On_Service_When_View_Loads()
{
    this.Setup();
    IService<Customer> serviceMock = repository.StrictMock<IService<Customer>>();

    IEventRaiser loadRaiser =
        Expect.Call(() => this.viewStub.Load += null).IgnoreArguments().GetEventRaiser();

    Expect.Call(serviceMock.GetById(4)).Return(new Customer());
    this.repository.ReplayAll();

    new CustomerPresenter(serviceMock, this.viewStub);
    loadRaiser.Raise(this.viewStub, EventArgs.Empty);
    this.repository.VerifyAll();
}

There are a few subtle differences from the original attach to load event test. I am now using a stub for the view, I set an expectation on the load event in order to get the event raiser, which I have called loadRaiser. This expectation on the stub will never be verified, meaning that the test is more robust to refactoring. I then set the expectation on the service that its’ GetById(4) is called finally setting the repository into replay mode. As in the attach test above, I instantiate the Presenter with the serviceMock and the viewStub. I then use the loadRaiser to Raise the load event, finally verifying that all expectations have been met. The implementation of the constructor now looks like this;

public CustomerPresenter(IService<Customer> service, ICustomerView view)
{
    this.Service = service;
    this.View = view;
    this.View.Load += ((sender, args) => service.GetById(4));
}

Conclusion

As I said from the outset, it is not straight forward, but my hope is that this series will be useful for those of you that wish to go down the route of incorporating dynamic mocking frameworks into your unit tests. This article should help you to avoid some of the pitfalls I went through in trying to understand the feedback from the framework. It should also go some way to convincing you that Rhino mocks gives you a lot of useful features to help you avoid the task of rolling your own fakes.

In the next article I will be writing about some of the new features in Rhino Mocks 3.5 beta and also comparing it with Moq to see which side of the religious argument I fall under.

Posted in Mock Object Frameworks, Test Doubles, Unit testing | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.