Search This Blog

2010-05-09

Using Fluent Builder Pattern to Configure Test Objects

Depending on the complexity of the domain model, configuring mock objects for specific cenarios can make the resulting test code to get messy.

Consider the situation below with C#, NUnit and Moq framework

[Test]
[ExpectedException(InvalidPaymentAgreementException)]
public void PaymentAgreementMustNotBeCreatedWhenThePaymentOptionIsNotValidForTheDebtType()
{
  Mock somePaymentOptionMock = new Mock();
  Mock debTypeMock = new Mock();
  debtTypeMock
    .Setup(debtType.GetPaymentOptions())
    .Returns(new List(){somePaymentOptionMock.Object});

  Mock anotherPaymentOptionMock = new Mock();

  Mock debtMock = new Mock();
  debtMock.Setup(debt.DebtType).Returns(debTypeMock.Object);            

  PaymentAgreement paymentAgreement = new PaymentAgreement(
    new PaymentAgreementCreationParameter()
    {
      AgreementYear = SystemDate.Get().Value.Year,
      AgreementNumber = 1,
      AgreementCreationDate = SystemDate.Get().Value.Date,
      NumberOfInstallments = 1,
      AgreementValue = 100.0m,
      Debts = new List() { debtMock.Object },
      SelectedPaymentOption =  anotherPaymentOptionMock.Object
    });
}

A developer who reads the unit test can take a consirable amount of time to understand what is actually being tested even if a well-designed mock framework such as Moq is in use. Most of this work is about configuring mock objects. Besides the code size, the unit test doesn´t speak the language of the domain (business) and thus it becomes a mass of meaningless mock configuration.
I am on my way to learn how to apply TDD effectvely in software development and I quickly realized that the quality of unit tests are very important in order to this kind of methodology to succeed.

Accidentally some days I read an interesting post from Andrian about Rich Domain Tests at http://adrianhummel.wordpress.com/ and I decided to apply his idea.
After reading his post I got to the conclusion that one way to solve or at least minimize this unit-test-messy-code-problem was by using a fluent builder pattern to configure mock objects by using a builder whose interface could be describe how I am configuring a mock object with an interface closer to domain language.

The unit test below is a rewritten from the example above with the concepts described here:

[Test]
[ExpectedException(InvalidPaymentAgreementException)]
public void PaymentAgreementMustNotBeCreatedWhenThePaymentOptionIsNotValidForTheDebtType()
{
  PaymentOption somePaymentOption = PaymentOptionMockBuilder
                                    .Begin()
                                    .BuildPaymentOption();

  DebtType debtType = DebtTypeMockBuilder
                      .Begin()  
                      .AddPaymentOptionOf(somePaymentOption)
                      .BuildDebtType();
            
  PaymentOption anotherPaymentOption = PaymentOptionMockBuilder
                                       .Begin()
                                       .BuildPaymentOption();          
            
  Debt debt = DebtMockBuilder
              .Begin()
              .WithDebtTypeOf(debtType)
              .BuildDebt();

  PaymentAgreement paymentAgreement = new PaymentAgreement(
    new PaymentAgreementCreationParameter()
    {
      AgreementYear = SystemDate.Get().Value.Year,
      AgreementNumber = 1,
      AgreementCreationDate = SystemDate.Get().Value.Date,
      NumberOfInstallments = 1,
      AgreementValue = 100.0m,
      Debts = new List &lt Debt &gt () { debt},
      SelectedPaymentOption =  anotherPaymentOption
    });

}

The fluent builder for Debt is DebtMockBuilder and can be programmed as follows:

    public class DebtMockBuilder
    {
        private Mock _debtMock;

        public static DebtMockBuilder Begin()
        {
            DebtMockBuilder builder = new DebtMockBuilder();
            builder._debtMock = new Mock();
            return builder;
        }

        public Debt BuildDebt()
        {
            return _debtMock.Object;
        }

        public DebtMockBuilder WithDebtTypeOf(DebtType debtType)
        {
            this._debtMock.Setup(debt => debt.DebtType).Returns(debtType);
            return this;
        }
    }

PaymentOptionMockBuilder follows the same idea.

Although I see that some improvements are needed I could see the following advantages from fluent mock builders:

  • The test code was easier to understand because domain terms were applied instead of specific API language.


  • Specific mock framework calls were encapsulated which theoretically can let programmers to use another mock framework in other projects or using more than one mock framework in the same test (I dont know why someone would do such a thing...).


  • Finally mock configuration becomes more flexible since existing methods don´t have to be modified to include new configuration but only a new configuration method is needed. Thus mock configuration can evolve as needed without loosing the domain interface.

2010-05-08

Test-Driven-Development Best Practices

I recently read a very intersting conversation in StackOverflow.com about test-driven development. I found it very instersting and the principles can be summarized as follows: (not ordered by importance)

1. Write the test first, then the code. Reason: This ensures that you write testable code and that every line of code gets tests written for it. 



2. Design classes using dependency injection. Reason: You cannot mock or test what cannot be seen. 


3. Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter. Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized. 


4. Do not write static methods or classes. Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them. 


5. Program off interfaces, not classes. Reason: Using interfaces clarifies the relationships between objects. An interface should define a service that an object needs from its environment. Also, interfaces can be easily mocked using Rhino Mocks and other mocking frameworks. 


6. Isolate external dependencies. Reason: Unresolved external dependencies cannot be tested. 


7. Mark as virtual the methods you intend to mock. Reason: Rhino Mocks is unable to mock non-virtual methods.

8. Use creational design patterns. This will assist with DI, but it also allows you to isolate that code and test it independently of other logic.



9. Write tests using Bill Wake's Arrange/Act/Assert technique. This technique makes it very clear what configuration is necessary, what is actually being tested, and what is expected.


10. Don't be afraid to roll your own mocks/stubs. Often, you'll find that using mock object frameworks makes your tests incredibly hard to read. By rolling your own, you'll have complete control over your mocks/stubs, and you'll be able to keep your tests readable. (Refer back to previous point.)


11. Avoid the temptation to refactor duplication out of your unit tests into abstract base classes, or setup/teardown methods. Doing so hides configuration/clean-up code from the developer trying to grok the unit test. In this case, the clarity of each individual test is more important than refactoring out duplication.


12. Implement Continuous Integration. Check-in your code on every "green bar." Build your software and run your full suite of unit tests on every check-in. (Sure, this isn't a coding practice, per se; but it is an incredible tool for keeping your software clean and fully integrated.)

Reference: http://stackoverflow.com/questions/124210/best-practices-of-test-driven-development-using-c-and-rhinomocks