Amazon.com Widgets October 2011

Flotsam and Jetsam #48

By Nick at October 29, 2011 10:51
Filed Under: Delphi, Flotsam and Jetsam

Flotsam and Jetsam #47

By Nick at October 18, 2011 03:52
Filed Under: Delphi, Flotsam and Jetsam

Delphi Mocks: The Basics

By Nick at October 16, 2011 12:41
Filed Under: Software Development, Delphi, Unit Testing

Introduction

As you may have noticed, I’ve kind of started to become a championship caliber pain in the butt about unit testing.  I walk the halls of Gateway Ticketing saying “If your code isn’t easy to test, you are doing it wrong”.  I keep giving my Unit Testing presentation to anyone that will listen.  But I feel justified – unit testing is critical to writing clean, maintainable code.

One of the reasons people seem to frequently give for not doing unit testing is that “My code requires <some external dependency> and it’s too hard to configure for simple unit tests” or something like that.  Okay, fair enough.  I won’t point out how you should be using Dependency Injection to decouple that code and enable you to insert a mock or a stub or a different class for testing purposes.  (Okay, I lied – technically I guess I did mention that.  Sorry.)  But I get that sometimes implementing a complete, formal TMockXXXX version of your interface (and you are coding against interfaces and not implementations, right?) is not something you want to do. 

Mocks

In their simplest form, a mock object is simply an alternate implementation of a class that provides “fake” responses to method calls.  For example, you have a class TCustomer that has a method GetCustomerName, and normally, that call goes to the production database and gets the name (a simple, unlikely example, I know, but you get the idea).  So to avoid the call to the database, you just create TMockCustomer, and implement it’s call to GetCustomerName and have it return “George Jetson” every time.  This enables you to test the class that is using TCustomer without having to hit the database at all.

But that can get a bit clumsy.  What if you want to return different values based on different inputs?  What if you find a bug based on specific input or output, and you want to create a unit test for that specific case?  Then a mock class as described above gets harried, complicated, and hard to maintain.

Enter a Mocking Framework

What if we could have a framework that would allow us to implement any interface, and define easily and exactly what the inputs and outputs should be?  That would be cool.  This would enable you to easily create a mock object that can respond to method calls in defined ways in a flexible, easy to set up manner.  This is what a mocking framework does.

Obviously something this flexible needs some powerful language features.  Such a framework would have to be able to flex to dynamically implement an interface.  It would have to be able to dynamically recognize method calls and respond accordingly.  Fortunately, Delphi XE2 is up to the task.  Delphi XE2 introduces the TVirtualInterface class that lets you dynamically implement any interface at runtime.  Combine that with the new RTTI, and you have the ability to build a very powerful mocking framework.

And that is just what Vince Parrett of VSoft Technologies, author of the wonderful FinalBuilder, did.  He has built a very cool and very powerful library called Delphi Mocks and released it as open source for all of us.  Very cool – thanks, Vince.   Delphi Mocks is available on GitHub under the very developer friendly Apache 2.0 License.  Vince has written a nice “Getting Started” guide, but I wanted to write  this article to build a very simple example of a pretty simple use case for mock objects.  So let’s do that.

An Expensive Service

A typical use case for using a mock object is to replace a service that is “expensive”.  Sometimes that means expensive as in “actually costs money”, but it will more likely mean expensive in CPU cycles, database connectivity, or anything else that requires an external dependency that causes your class under test to stop being tested in isolation and start being integrated with something else.   Since a unit test should always test something atomically and leave nothing (database entries, files, charges on a credit card) lying around, any time that will happen when running a unit test, you probably should consider a stub or a mock object instead.

By “stub” I mean “a class that implements a particular interface but doesn’t really do anything”.  It’s not exactly the same as a mock object in that the interface in question will normally not return anything but merely do things external to the class.  A typical example is a logging class.  If you are running unit tests, you don’t want your logging system writing logs all over the place every time you run your tests, so you create a Logger stub class that acts like your regular logger, but which actually doesn’t do anything.  You can call it in your code, but you get nothing from it – which is what you want. 

So let’s look at a simple, but “expensive” service.  Consider the following code:

unit uCreditCardValidator;

interface

uses
      SysUtils;

type

  ICreditCardValidator = interface(IInvokable)
  ['{68553321-248C-4FD4-9881-C6B6B92B95AD}']
    function IsCreditCardValid(aCreditCardNumber: string): Boolean;
    procedure DoNotCallThisEver;
  end;

  TCreditCardValidator = class(TInterfacedObject, ICreditCardValidator)
    function IsCreditCardValid(aCreditCardNumber: string): Boolean;
    procedure DoNotCallThisEver;
  end;

implementation

uses
     Dialogs;

{ TAdder }

function TCreditCardValidator.IsCreditCardValid(aCreditCardNumber: string): Boolean;
begin
  // Let's pretend this calls a SOAP server that charges $0.25 everytim
  // you use it.

  // For Demo purposes, we'll have the card be invalid if it the number 7 in it
  Result := Pos('7', aCreditCardNumber) <= 0;

  ShowMessage('You were just charged $0.25');
end;

procedure TCreditCardValidator.DoNotCallThisEver;
begin
  // This one will charge the company $500!  We should never
  // call this!
end;

end.

This unit declares two things, an ICreditCardValidator and a class that implements it, TCreditCardValidator.  It simulates deciding a credit card is bad by saying any card number that has the number ‘7’ in it is bad.  Otherwise, any string will be acceptable. It’s a demo class, obviously, but it illustrates a class that would be used only in production, as you get charged by a credit card validating service every time you call IsCreditCardValid.    Clearly, you don’t want to be calling that whenever you run your tests.  Thus, it seems likely that any collection of unit tests that wants to use this service would likely want to use a mock class.

A Class to Use the ICreditCardValidator

Mock classes really become useful when you are testing a class that consumes an expensive service.  Thus, we’ll declare the following class, TCreditCardManager, which consumes ICreditCardValidator:

unit uCreditCardManager;

interface

uses
      uCreditCardValidator
    ;

type
  TCreditCardManager = class
  private
    FCCValidator: ICreditCardValidator;
  public
    constructor Create(aCCValidator: ICreditCardValidator);
    function CreditCardIsValid(aCCString: string): Boolean;
  end;

implementation

{ TAddingMachine }

function TCreditCardManager.CreditCardIsValid(aCCString: string): Boolean;
begin
  Result := FCCValidator.IsCreditCardValid(aCCString);
end;

constructor TCreditCardManager.Create(aCCValidator: ICreditCardValidator);
begin
  inherited Create;
  FCCValidator := aCCValidator;
end;

end.

This class is really simple – it just takes an ICreditCardValidator in it’s constructor and uses it to validate credit cards.  As a demo class it is really simple, but a more complete class would have methods to make payments against the card, etc.  But if, when testing this class, you pass it in an implementation of the ICreditCardValidator above, you’ll get charged $0.25 for every test you run.  That’s not something you’d really want to do, so this class seems like a good candidate for using a mock object to replace the implementation of ICreditCardValidator

Testing TCreditCardManager Can Be Expensive

So, the typical way to test TCreditCardManager might look like this:

procedure TestTCCValidator.TestValidateCreditCard;
var
  ReturnValue: Boolean;
  ExpensiveCCValidator: ICreditCardValidator;
  ValidCard: string;
  BadCard: string;
begin
  ExpensiveCCValidator := TCreditCardValidator.Create;
  FCCValidator := TCreditCardManager.Create(ExpensiveCCValidator);

  ValidCard := '1112221'; // Rule is that a bad card has a '7' in it
  BadCard   := '6667666'; // ..so this one is bad

  ReturnValue := FCCValidator.CreditCardIsValid(ValidCard);
  CheckTrue(ReturnValue);

  ReturnValue := FCCValidator.CreditCardIsValid(BadCard);
  CheckFalse(ReturnValue);
end;

However, if you run this in the GUI test runner for DUnit, you’ll see this:

image

 

And of course, if you keep this up, the bill you get will not make your boss happy.

Testing with a Mock

So, to avoid the wrath of your boss, you should create a mock object that behaves like you want it to but that doesn’t end up costing anything.  The first way you might do it is to create a new class that implements the ICreditCardValidator interface, but that does nothing or returns set values.  But that is kind of clunky, and hard to customize.  What you really want is what I mentioned earlier, an extensible mock that can be created an configured on the fly.  That’s where Delphi Mocks comes in.

The Delphi.Mocks.pas unit declares a type TMock which takes a parameterized type, and which then can sort of morph itself into an implementation of that interface using the cool new-to-XE2 class called TVirtualInterfaceTVirtualInterface basically allows you to implement an interface on the fly at runtime.  Thus, you can create a generic class (or record, in the case of TMock) that can appear to be any interface you want it to be. 

Thus, we can create a TMock that looks and acts like an ICreditCardValidator:

var
  CCMock: TMock<ICreditCardValidator>;
 begin
  CCMock := TMock<ICreditCardValidator>.Create;
  ...
end;

Once we have that mock, we can tell it how to behave:

  ValidCard := '1112221'; // Rule is that a bad card has a '7' in it
  BadCard   := '6667666'; // ..so this one is bad

  CCMock.Setup.WillReturn(True).When.IsCreditCardValid(ValidCard);
  CCMock.Setup.WillReturn(False).When.IsCreditCardValid(BadCard);

This code uses a nice fluent interface to be somewhat self-explanatory.  It basically sets the mock up as follows: “When I pass in the valid string, return True.  When I pass in the bad string, return False.”  This is a basic definition that will allow your TCreditCardManager class to exercise itself with both good and bad input, allowing you to test your code with both kinds of responses.  We can determine exactly what the inputs and outputs are and ensure that the mock displays the correct behavior and follows the business rules set out in the “real” implementation.  Notice, too, that the When call, through the delightful magic of generics, is actually an implementation of the ICreditCardValidator interface, and thus is able to execute a real method call to the method from that interface.  You even get support from Code Completion in the IDE. 

Now, you can create the Credit Card Manager, pass it your mock object, and run tests with your mock input and output:

  FCCValidator := TCreditCardManager.Create(CCMock);

  ReturnValue := FCCValidator.CreditCardIsValid(ValidCard);
  CheckTrue(ReturnValue);

  ReturnValue := FCCValidator.CreditCardIsValid(BadCard);
  CheckFalse(ReturnValue);

This way, you can exercise the instance and test it  to your hearts content without incurring any of the expense associated with your “regular” implementation.  If you need to add additional tests, you can simply tell the mock class what the new input and outputs are, and then run the appropriate tests.

Ensuring Code Is (or Is Not) Called

When writing tests, there may be times when you want to ensure that a given method is called with a frequency that you want to specify.  Thus, you can write things like:

  CCMock.Setup.Expect.AtLeastOnce.When.IsCreditCardValid(ValidCard);

  // Ensure that the tests never call this.  It costs $500!!
  CCMock.Setup.Expect.Never.When.DoNotCallThisEver;

And then, when all the test are run, call:

CCMock.Verify;

on the mock object, and it will validate that the calls that you required were indeed called. 

So, in the above example, if I were to call:

CCMock.Instance.DoNotCallThisEver;

I would get the following dialog:

image

…which of course tells me that I called a method in my tests that should not have ever been called.

There are also methods on the call to Expect interface that ensure that a certain call is made a minimum or maximum number of times, between a specified  number of times, at least or at most a certain number of times, and as we saw, even never.  Also, you can specify that one method be called before or after other methods.  This enables you to dictate exactly how your object methods are called, and what should or should not happen when you run your tests.

Conclusion

So the Delphi Mock library is a very powerful tool for making it easy to write concise unit tests that don’t connect to “expensive” classes that could make testing difficult.  The goal of writing testable code is a worthy one, and Delphi Mocks definitely can make it easier to reach that goal.

Getting Giddy with Dependency Injection and Delphi Spring #7 – Controlling Construction

By Nick at October 08, 2011 12:47
Filed Under: Software Development, Delphi

As always, you can download the Delphi Spring Framework from GoogleCode.

By now you should be getting the idea about dependency injection – how you can use it to decouple your code and provide instances of your objects.  Hopefully you see the benefits of coding against interfaces and not implementations.  And if things are going really well, you are writing unit tests with ease because your code is easily tested. 

However, I bet by now some of you are thinking that this looks really cool and all, but there is just a touch too much “magic” going on – that there is a bit too much going on under the covers.

Well, you are right about that – there is a lot going on under the covers.  The Delphi Spring Framework does a lot of work for you, mainly by creating instances of classes using Run-time Type Information (RTTI).  It controls the creation, and can even let you manage the lifetime of those objects.

But I also bet that some of you are a bit uncomfortable with the notion of relying on all that magic.  While turning over that control will work in many cases, you don’t always want to give up control over the  creation of your objects. 

Well, you don’t have to.  The framework allows you to customize the way that your classes are created if you so desire.  Very often, if your classes are well designed – your constructors are simple, you aren’t doing much more than assigning values – you don’t need to do anything special when you construct an instance.  But sometimes you do.  Sometimes, your class needs to be passed something dynamic – a class whose state can only be known at runtime.    For instance, you may have a given customer, and that customer has invoices, and you have a class that you want to pass that customer to, but you also want to completely decouple that class.  Your customer is dynamic – you may be running a query and need to perform this operation on every customer in your database. Or maybe the customer is doing something on your website, and so your customer object is specific to that customer.  In any event, the customer data is dynamic at runtime, and so the creation of an object can’t be cookie-cutter.  It has to be unique each time you need an instance of this object that takes action on the given customer. 

The code below comes from the Samples directory of the Delphi Spring Framework.  It’s part of the Demo.Spring.DelegatedConstructor project

The Spring Framework lets you control the creation of your objects through a method on the TRegistration class – the class used to register types against interfaces.  As part of registering your class, you can pass an anonymous method of type TActivatorDelegate, which his declared as:

TActivatorDelegate<T: class> = reference to function: T;

The TRegistration class uses the fluent interface, so you can chain together a number of things that you want to attach to any given registration.  So, for instance, if you have a project involving a TUser class, and the TUser class is dynamic, then a class (such as TUpgradeUser) which needs a TUser, might be registered as follows:

  GlobalContainer.RegisterType<TUserProcessor>.Implements<IUserUpgrader>.AsTransient.DelegateTo(
    function: TUserProcessor
    begin
      Result := TUserProcessor.Create(GetCurrentUser);
    end
  );

The TUserProcessor class is registered as implementing the IUserUpgrader interface.  The lifetime of the resulting class is set to be “Transient” meaning that the implementing class will live “normally”; that is, it will be destroyed when the interface reference goes out of scope.  (Note that AsTransient is the default lifetime.  We’ll discuss container lifetime management in a future blog post). 

Finally, the actual creation of the TUserProcessor class is “delegated to” an anonymous method – a function in this case, as noted above – that simply returns an instance of the TUserProcessor class.  The key here, of course, is that the anonymous method can call the GetCurrentUser routine which will inject the current, dynamic TUser instance into the resulting object.  You can do anything you want in this anonymous method, including creating and setting up the resulting object in any manner you choose.  You could set properties and even call methods on the resulting, implementing object. 

If you examine the code for the project, you’ll note, of course, that it doesn’t actually do anything other than write to the console.  The GetCurrentUser call is merely a singleton returning the same instance of TUser.   The code is merely illustrative, and so the “background stuff” doesn’t really do anything.  In a real application, a call to GetCurrentUser would do just that, return an instance of TUser that represented the current, dynamic state of the user in question.   The critical part to note is that you can control the creation of the TUserProcessor to as large a degree as you want. 

Finally, when you actually call the ServiceLocator to grab an instance, the Container will call your anonymous method and return an instance constructed exactly like you want it to be constructed.

So in the end, the Spring Container gives you total control – if you want it – over the creation of your objects.  If you need to, you can have a little control over the “magic” that takes place and sprinkle your own little fairy dust on the construction process.

Fun Code of the Week #1

By Nick at October 06, 2011 11:20
Filed Under: Delphi, Fun Code
unit uIsPalindrome;

interface

function IsPalindrome(const aString: string): Boolean;

implementation

uses
       Spring.Collections
     , {$IF CompilerVersion >= 230}System.{$IFEND}SysUtils
     ;

function CleanString(const aString: string): string;
var
  C: char;
begin
  // Remove all non-alpha chars and make all lower case
  // Spaces don't matter, so let's count only letters
  Result := '';
  for C in LowerCase(aString) do
  begin
    if CharInSet(C, ['a'..'z', 'A'..'Z']) then
    begin
      Result := Result + C;
    end;
  end;
end;

function IsPalindrome(const aString: string): Boolean;
var
  Stack: IStack<Char>;
  C: Char;
  NoSpaces: string;
  Temp: string;
begin
  NoSpaces :=  CleanString(aString);

  Stack := TCollections.CreateStack<Char>;
  for C in NoSpaces do
  begin
    Stack.Push(C);
  end;
  Temp := '';
  repeat
    Temp := Temp + Stack.Pop;
  until Stack.Count = 0;
  Result := Temp = NoSpaces;
end;

end.

Added: I always enjoy posting code like this. Note that it is entitled "Fun Code", not "Highly optimized, perfectly written Code". ;-)

Flotsam and Jetsam #46

By Nick at October 05, 2011 13:58
Filed Under: Delphi, Flotsam and Jetsam
  • I will be speaking this year at CodeRage 6.  I’m giving two talks, one on Dependency Injection, and one on Unit Testing.  Please attend.  I think my talks in particular will be really good.  But maybe not as good as all the other stuff you can learn there
  • Are you aware of the fact that FireMonkey, RAD Studio, and Delphi all have spanking new pages on Facebook?  I wasn’t.  And they do.
  • Holy crap!  Allen Bauer is alive!
  • I’ve been trying to write some more example applications for the Delphi Spring Framework, and so I was researching the Factory Pattern to see if I could find a good illustration to build an example for (TFoo and TBar can only take you so far….) and I ran across a nice article on MSDN that describes it nicely.  It actually has a nice example of a “Computer Factory”, and I’ll likely riff of that to create a “real world” example of a physical object.  But the part that caught my notice, and caused me to write this entry was a quote at the beginning:  “When was the last time someone asked the designers of the Empire State building to add ten new floors at the bottom, put a pool on the top, and have all of this done before Monday morning?” And the answer, of course, is “never”.  Winking smile  Anyway, it just was another data point in my ongoing contention that software developers are not engineers. 
  • This is a pretty amazing and thorough tutorial on LiveBindings.  Live Bindings is one of those cool features that I need to learn about and that appears to be cool now, with the potential to get a lot cooler in the future.

My Book

A Pithy Quote for You

"There's a fine line between fishing and just standing on the shore like an idiot."    –  Steve Wright

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.