in

 

Jimmy Bogard

Chief disinformation radiator

March 2008 - Posts

  • PTOM: The Dependency Inversion Principle

    The Dependency Inversion Principle, the last of the Uncle Bob "SOLID" object-oriented design principles, can be thought of the natural progression of the Liskov Substitution Principle, the Open Closed Principle and even the Single Responsibility Principle.  This post is the latest in the set of SOLID posts:

    The Dependency Inversion Principle, or DIP, is often used interchangeably with Dependency Injection and Inversion of Control.  However, following DIP does not mean we must automatically use a IoC container like Spring.NET, Windsor or StructureMap.  IoC containers are tools to assist in applications adhering to DIP, but we can follow DIP without using IoC containers.

    The Dependency Inversion Principle states:

      • High level modules should not depend upon low level modules.  Both should depend upon abstractions.
      • Abstractions should not depend upon details.  Details should depend upon abstractions.

    The DIP can be a little vague, as it talks about "abstractions" but doesn't describe what is being abstracted.  It speaks of "modules", which don't have much meaning in .NET unless you consider "modules" to be assemblies.  If you're looking at Domain-Driven Design, modules mean something else entirely.

    The Dependency Inversion Principle, along with the other SOLID principles, are meant to alleviate the problems of bad designs.  The typical software I run into in existing projects has code organized into classes, but it still isn't easy to change.  I usually see big balls of mud along with a crazy spider web of dependencies where you can't sneeze without breaking code on the other side of the planet.

    Spider webs and bad design

    Bad designs and bad code is bad because it's hard to change.  Bad designs are:

    • Rigid (change affects too many parts of the system)
    • Fragile (every change breaks something unexpected)
    • Immobile (impossible to reuse)

    Some people's ideas of "bad design" would be something like seeing string concatenation instead of a StringBuilder.  While this may not be the best performing choice, string concatenation isn't necessarily a bad design.

    It's pretty easy to spot bad designs.  These are sections of code or entire applications that you dread touching.  A typical example of rigid, fragile and immobile  (bad) code would be:

    public class OrderProcessor
    {
        public decimal CalculateTotal(Order order)
        {
            decimal itemTotal = order.GetItemTotal();
            decimal discountAmount = DiscountCalculator.CalculateDiscount(order);
    
            decimal taxAmount = 0.0M;
    
            if (order.Country == "US")
                taxAmount = FindTaxAmount(order);
            else if (order.Country == "UK")
                taxAmount = FindVatAmount(order);
                
            decimal total = itemTotal - discountAmount + taxAmount;
    
            return total;
        }
    
        private decimal FindVatAmount(Order order)
        {
            // find the UK value added tax somehow
            return 10.0M;
        }
    
        private decimal FindTaxAmount(Order order)
        {
            // find the US tax somehow
            return 10.0M;
        }
    }
    

    The OrderProcessor sets out to do something very simple: calculate the total of an Order.  To do so, it needs to know the item total of the order, any discounts applied, as well as the tax amount (which depends on the Order's Country).

    Too many responsibilities

    To see why the DIP goes hand-in-hand with the Single Responsibility Principle, let's list out the responsibilities of the OrderProcessor:

    • Knowing how to calculate the item total
    • Finding the discount calculator and finding the discount
    • Knowing what country codes mean
    • Finding the correct taxing method for each country code
    • Knowing how to calculate tax for each country (commented out for brevity's sake)
    • Knowing how to combine all of the results into the correct final total

    If a single class (or a single method in this case) answers too many questions (how, where, what, why etc.), it's a good indication that this class has too many responsibilities.

    To move towards a good design, we need to remove the external dependencies of this class to pare it down to its core responsibility: finding the order total.  Offhand, the dependencies I see are:

    • DiscountCalculator
    • Tax decisions

    In the future, we might need to support more countries, which means more tax services, and more responsibilities.  To reduce the rigidity, fragility and immobility of this design, we need to move these dependencies outside of this class.

    Towards a better design

    When following the DIP, you notice that the Strategy pattern begins to show up in a lot of your designs.  Strategy tends to solve the "details should depend on abstractions" part of the DIP.  Factoring out the DiscountCalculator and the tax decisions, we wind up with two new interfaces:

    • IDiscountCalculator
    • ITaxStrategy

    I'm not a huge fan of the "ITaxStrategy" name, but it will suffice until we find a better name from our model.

    Factoring out the dependencies

    To factor out the dependencies, first I'll create a couple of interfaces that match the existing method signatures:

    public interface IDiscountCalculator
    {
        decimal CalculateDiscount(Order order);
    }
    
    public interface ITaxStrategy
    {
        decimal FindTaxAmount(Order order);
    }
    

    Now that I have a couple of interfaces defined, I can modify the OrderProcessor to use these interfaces instead:

    public class OrderProcessor
    {
        private readonly IDiscountCalculator _discountCalculator;
        private readonly ITaxStrategy _taxStrategy;
    
        public OrderProcessor(IDiscountCalculator discountCalculator, 
                              ITaxStrategy taxStrategy)
        {
            _taxStrategy = taxStrategy;
            _discountCalculator = discountCalculator;
        }
    
        public decimal CalculateTotal(Order order)
        {
            decimal itemTotal = order.GetItemTotal();
            decimal discountAmount = _discountCalculator.CalculateDiscount(order);
    
            decimal taxAmount = _taxStrategy.FindTaxAmount(order);
    
            decimal total = itemTotal - discountAmount + taxAmount;
    
            return total;
        }
    }
    

    The CalculateTotal method looks much cleaner now, delegating the details of discounts and tax to the appropriate abstractions.  Instead of the OrderProcessor depending directly on details, it depends solely on the abstracted interfaces we created earlier.  The specifics of how to find the correct tax method is now encapsulated from the OrderProcessor, as is the hard dependency on a static method in the DiscountCalculator.

    Filling out the implementations

    Now that we have the interfaces defined, we need actual implementations for these dependencies.  Looking at the DiscountCalculator, which is a static class, I find that I can't immediately change it to a non-static class.  There are many other places with references to this DiscountCalculator, and since it's the real world, none of these other places have tests.

    Instead, I can just use the Adapter pattern to adapt the interface I need for an IDiscountCalculator:

    public class DiscountCalculatorAdapter : IDiscountCalculator
    {
        public decimal CalculateDiscount(Order order)
        {
            return DiscountCalculator.CalculateDiscount(order);
        }
    }
    

    In applying the Adapter pattern, I just wrap the real DiscountCalculator in a different class.  The advantage of the Adapter pattern in this case is that the existing DiscountCalculator can continue to exist, but if when the mechanism for calculating discounts changes, my OrderProcessor does not need to change.

    For the tax strategies, I can create two implementations for each kind of tax calculation being used today:

    public class USTaxStrategy : ITaxStrategy
    {
        public decimal FindTaxAmount(Order order)
        {
        }
    }
    
    public class UKTaxStrategy : ITaxStrategy
    {
        public decimal FindTaxAmount(Order order)
        {
        }
    }
    

    I left the implementations out, but I basically moved the methods from the OrderProcessor into these new classes.  Neither of the original methods used any instance fields, so I could copy them straight over.

    My OrderProcessor now has dependencies factored out, so its single responsibility is easily discerned from looking at the code.  Additionally, the implementations of IDiscountCalculator and ITaxStrategy can change without affecting the OrderProcessor.

    Isolating the ugly stuff

    For me, the DIP is all about isolating the ugly stuff.  For calculating order totals, I shouldn't be concerned about where the discounts are or how to decide what tax strategy should be used.  We did increase the number of classes significantly, but this is what happens when we move away from a procedural mindset to a true object-oriented design.

    I still have the complexity to solve of pushing the dependencies into the OrderProcessor.  Clients of the OrderProcessor now have the burden of creating the correct dependency and giving them to the OrderProcessor.  But that problem is already solved with Inversion of Control (IoC) containers like Spring.NET, Windsor, StructureMap, Unity and others.

    These IoC containers let me configure the "what" when injecting dependencies, so even that decision is removed from the client.  If I didn't want to go with an IoC container, even a simple creation method or factory class could abstract the construction of the OrderProcessor with the correct dependencies.

    By adhering to the Dependency Inversion Principle, I can create designs that are clean, with clearly defined responsibilities.  With the dependencies extracted out, the implementation details of each dependency can change without affecting the original class.

    And that's my ultimate goal: code that is easy to change.  Easier to change means a lower total cost of ownership and higher maintainability.  Since we know that requirements will eventually change, it's in our best interest to promote a design that facilitates change through the Dependency Inversion Principle.

    Posted Mar 31 2008, 04:52 PM by bogardj with 6 comment(s)
    Filed under:
  • Stop creating custom delegate types

    Note to OSS and framework developers:

    Please stop creating custom delegate types.  Use the Action and Func delegates instead.

    The problem is that delegate types with the same signature are not convertible to each other.  For example, none of these assignments will work:

    public delegate bool CustomMatchingFunction(string value);
    
    public void Custom_delegates_are_bad()
    {
        Predicate<string> match1 = value => value == "Blarg";
        Func<string, bool> match2 = value => value == "Blarg";
        CustomMatchingFunction match3 = value => value == "Blarg";
    
        match1 = match2;
        match1 = (Predicate<string>)match2;
        match1 = match3;
    }
    

    Although all of the delegate types shown have the same signature, this does not mean that they're the same type.  They're neither implicitly nor explicitly convertible from each other.  One of the preliminary LINQ framework design guidelines states:

    Do use the new LINQ types "Func<>" and "Expression<>" instead of custom delegates and predicates, when defining new APIs.

    There are Action delegates for void methods and Func delegates for methods that return values.  If something needs a delegate, use either the generic or specific versions of these delegate types.  Instead of "Predicate<T>", use "Func<T, bool>".  Instead of creating a custom void delegate, use "Action".

    By creating custom delegate types, you're forcing people using your API to either force your custom type into their code, or force them to use a bunch of "wrapper methods" that wrap, convert and call your custom delegate type.

    If you declare even a single delegate type in your code (and you're using .NET 3.5), stop and make sure there isn't already an Action or Func delegate that works for you.

    Posted Mar 26 2008, 10:03 AM by bogardj with 17 comment(s)
    Filed under:
  • Looking for Extreme Programmers in Austin, TX

    As was announced on Jeffrey's blog, Headspring is hiring Extreme Programmers.  We have several positions to fill, so if you're interested in joining the leading agile consulting company in Austin, please apply through our job posting.

    We're a small company with a startup feel, but without the baggage of a startup.  We practice TDD, we're co-located, continuous integration is a given, and we work in 1-2 week iterations.  If any of this means anything to you, we're interested in talking to you.

    For more information, check out:

    Posted Mar 25 2008, 02:50 PM by bogardj with 3 comment(s)
    Filed under:
  • Variations on a Func-y theme

    Delegates have come a long way since C# 1.0 debuted back in early 2002.  The progression from using delegate parameters (outside of events) grew from quite cumbersome to fairly expressive with Lambda expressions with C# 3.0.  Functional style programming has become easier (some say feasible) with generics, lambdas and expression trees.

    But it wasn't always quite so easy.  To fully appreciate the possibilities a functional-style API gives us, I like to crack open the history books and examine how delegates have changed in C# throughout the years.

    Manual class creation: C# 1.0

    Suppose I want to search a list of books by author and return the first matching book.  For these examples, I'll assume I have the full Enumerable extensions, but search methods could be created manually by declaring special delegates.  But for simplicity's sake, I'll just use the FirstOrDefault(TSource) extension method.

    In C# 1.0, I had to create a special class to perform the matching:

    public Book FindByAuthor(string author)
    {
        List<Book> books = GetBooks();
    
        MatchesAuthorSpecification spec = new MatchesAuthorSpecification(author);
    
        return books.FirstOrDefault(spec.IsSatisfiedBy);
    }
    

    After getting the list of books, I create a MatchesAuthorSpecification, initializing the spec object with the author I'm trying to find.  Here's the specification class:

    public class MatchesAuthorSpecification
    {
        private readonly string _author;
    
        public MatchesAuthorSpecification(string author)
        {
            _author = author;
        }
    
        public bool IsSatisfiedBy(Book book)
        {
            return book.Author == _author;
        }
    }
    

    The FirstOrDefault method expects a delegate to perform the matching, specifically a Func<TSource, bool> predicate.  All this means is that it needs a method that takes a Book and returns a bool.  The "IsSatisfiedBy" method matches that signature, so my little Specification class works to perform the author matching.

    The Specification pattern is great, but if I don't need that class outside of this FindByAuthor method, it's not doing much for me.  With C# 1.0, I didn't have a choice in the matter, I have to pass in a concrete method name to the FirstOrDefault method.

    Anonymous methods on the move: C# 2.0

    With C# 2.0 came anonymous methods.  I could now create little method snippets inside other methods, without needing to create special classes or other methods to hold the logic.

    Additionally, these anonymous methods supported closures, which allow anonymous methods to reference the scope they were created in.  This allows me to reference local variables inside the method block, with a bunch of compiler magic taking care of the rest.

    Using anonymous methods, my FindByAuthor method now looks like:

    public Book FindByAuthor(string author)
    {
        List<Book> books = GetBooks();
    
        return books.FirstOrDefault(delegate(Book book) { return book.Author == author; });
    }
    

    The body of the anonymous method looks exactly like the C# 1.0 version, without the need to create a class around it.  Note that the anonymous method refers to the "author" variable passed in to the method.  The anonymous method "remembers" what the local author variable is when the anonymous method is declared.  This allows the Find method to work properly.

    Anonymous delegates were a nice addition, but they could get ugly fairly quickly.  You never wanted more than two or three lines in these anonymous methods, but even one line didn't look great.  It's hard to discern exactly what's going on with all of the braces, keywords and statements around.

    Lambda expressions: C# 3.0

    Lambda expressions are finally available with C# 3.0.  Lambda expressions offer a much terser syntax for creating anonymous methods.  But it turns out there are two types of lambdas:

    • Statement lambdas
    • Expression lambdas

    Statement lambdas look almost exactly like anonymous methods, with the "delegate" keyword removed:

    public Book FindByAuthor(string author)
    {
        List<Book> books = GetBooks();
    
        return books.FirstOrDefault(book => { return book.Author == author; });
    }
    

    Lambda expressions also include the lambda operator "=>" to associate the statement or expression block with the input parameters.  In the above example, the type of "book" is inferred from the underlying delegate type (Func<Book, bool>).  This format is an improvement on anonymous methods, but the statement block still looks strange inside another method call.

    With expression lambdas, I can make the syntax about as terse as it gets:

    public Book FindByAuthor(string author)
    {
        List<Book> books = GetBooks();
    
        return books.FirstOrDefault(book => book.Author == author);
    }
    

    Now that's readable!  No extra class to define, just a short lambda expression describing the matching function.  The compiler can look at the expression lambda and infer the operation based on its result.  Since the expression shown returns a boolean, the C# compiler infers that this is what the method should return.

    Looking at each implementation in .NET Reflector, each implementation from the manual class creation to lambda expression is almost exactly the same.

    Lambdas are your friend

    Delegates have come a long way since C# 1.0, with C# 3.0 allowing powerful functional programming concepts like closures, currying, folding and others.

    Entire algorithms can be abstracted and the varying parts passed in as delegates.  The entire System.Linq.Enumerable set of extension methods is based on this concept of extracting algorithms.  With the simplicity of lambda expressions, new avenues of removing duplication are opened up.

    Posted Mar 22 2008, 01:15 PM by bogardj with 4 comment(s)
    Filed under:
  • Is your process dead?

    Two of the conventional criteria for exhibiting life are:

    • Adaptation
    • Response to stimuli

    Together these combine into the ability to respond to outside forces.  So how do we know if your process is dead?  If your team or organization:

    • Does not elicit feedback on a regular basis
    • Cannot respond to feedback

    Then your process is dead.

    Eliciting feedback

    In process control systems, stability is achieved by measuring output and incorporating that data back into the system.  Consider driving down a straight road.  No matter how straight you point the wheel initially, your car will eventually veer off course.

    To keep straight, you make regular observations on how straight you are and make small changes.  Wait too long to make changes and you'll likely meet the rumble strips, the shoulder, or another vehicle.

    By eliciting feedback early and often, we have the information required to make small changes to correct our course.  One of the XP values is feedback, which manifests itself through the practices of testing, retrospectives, continuous integration and others.

    Responding to feedback

    Now that you're making frequent observations, your engineering processes have to be tuned to be able to respond to that feedback.  If you drive an old beater car where you can only turn the wheel once a minute, making directional observations every second won't ensure a comfortable ride.  I'll be able to see myself driving off the cliff, but I have only two options: jump out of the car or ride it out Thelma and Louise style.

    Although Scrum elicits feedback, your team will not be able to respond to that feedback unless it's a well oiled machine.  That's where the engineering values, principles and practices of XP come into play.  By following XP, your team can respond to the mountain of feedback Scrum introduces to the system.

    If your organization is looking to adopt Scrum, keep in mind the engineering practices of XP.  Without them, you're on a straight line to a dead process.

    Posted Mar 20 2008, 07:31 PM by bogardj with 2 comment(s)
    Filed under:
  • Controller bloat?

    Some of my background information first:

    • 2 years classic ASP (ASP 3.0)
    • 5 years ASP.NET
    • 1-2 months MonoRail
    • 10 minutes ASP.NET MVC
    • ~45 seconds Ruby on Rails

    That's the sum of my experience with different web application frameworks.  Obviously it's weighted towards ASP.NET WebForms.  Having completed a project with MonoRail and looking at ASP.NET MVC, I can't help but feel that the Controller and the accompanying Context objects seem bloated.

    Now, I've already shown I'm no MVC expert, not even close.  But this seems a little bloated for something that's supposed to be lightweight:

    Sorry about the size, but it's nice to see it in all its glory.  That's the MonoRail Controller and RailsEngineContext (the HttpContext-like object of MonoRail).  Controller depends quite a bit on the IRailsEngineContext, so you can't really do much with a Controller in a unit test without mocking out the entire IRailsEngineContext and all of its properties (IResponse, IRequest, etc.).

    Here's the ASP.NET MVC Controller and Context from the Preview 2 drop:

    The Controller is smaller, but the Context is larger.  Again, the Controller makes heavy use of the HttpContextBase (formerly IHttpContext), as shown in Scott Hanselman's recent podcasts.

    Having next to zero experience with other MVC frameworks like Rails or Merb, I'm really curious to see how lightweight their controllers are.  I'm not sure lightweight controllers matters, or if the idea of a POCO controller would do anything.  Since we have to inherit from a Controller base class, we're saddled with its weight.

    I'll repeat again: I'm not an MVC expert.  But these controllers seem bloated to me and their accompanying Context objects seem bloated, as if I need to give the controller the IKitchenSink to get it to work under test.  Does anyone else get this feeling too?

  • Mapping options in LINQ to SQL

    A recent thread on the ALT.NET message board asked:

    How does everyone create the DataContext for their DB?

    1. Do you use the IDE and generate your custom .dbml (which also generates all your DTO's)?
    2. Do you use a generic DataContext object and just .GetTable<>() and create your DTO's by hand?

    Some of the comments indicated there were other mapping options other than the designer mapping I had seen 50 million times before in demos.  I bought LINQ in Action this past weekend to get the scoop. It turns out there are four (count 'em, four) ways of mapping your LINQ to SQL entities DTO's:

    • VS designer
    • Command-line SqlMetal tool
    • Hand-coded with attributes
    • Hand-coded with external XML files

    Take a real close look at that last one.  Reaaal close.  Now three times fast:

    LINQ to SQL supports persistence ignorance

    LINQ to SQL supports persistence ignorance

    LINQ to SQL supports persistence ignorance!

    You read that right folks, LINQ to Entities does not support persistence ignorance, but LINQ to SQL does!  Perhaps one of these teams should talk to the other.

    So is it the real deal?

    I ordered the options from most to least intrusive on your entity objects.  Obviously, the designer does not support a very maintainable solution, as it will run into the same issues of the last fifty drag-and-drop database products.

    SqlMetal can help create your initial entities, but this is from a DB-first perspective, which I don't run into for greenfield projects.  I don't create my database first, I create entities first, so this won't help me unless I run into an existing database.  In that case, I probably still won't use the tool, as existing databases can be their own form of crazy legacy code.

    Hand-coding with attributes allows me to decorate my classes, but it tends to clutter up my entities.  I don't want to look at my business objects and see a mess of persistence decorations.

    Finally, the external XML files.  Now I'm pretty much where I am with NHibernate, except in a much more primitive version.  The mappings are nowhere close, not even in the same ballpark as NHibernate's options.  LINQ to SQL is strictly table-per-class, and collection mappings aren't that hot.  Additionally, I wind up having to repeat a lot of the same information.

    Finally, I have to specify the location of the XML file whenever I create the DataContext object.  I have a few options, but basically LINQ to SQL has no mechanism that I see to "figure out" where the mapping might be.

    For me, the final verdict is: Though LINQ to SQL gives me powerful strongly-typed querying abilities with LINQ, the only maintainable mapping option still pales in comparison to NHibernate.

    Whether or not LINQ to SQL queries belong anywhere but inside your Repositories is another question...

  • Review - xUnit Test Patterns

    I consider one of the measures of quality of a book to be the number of personal assumptions challenged by its material.  To that point, Gerard Meszaros' xUnit Test Patterns did not disappoint.

    Perhaps the biggest assumption was a dogmatic view of what a unit test should look like without compromise.  There are benefits and liabilities to any choice made on test strategy, structure, organization, direction, and others.  Having options leads to making informed decisions instead of blindly following habits.  Looking back at my personal testing strategy over the past years, I fear I may have fallen into the latter.

    Some of the major items I look to implement include:

    • Rigor in addressing test smells
    • Fitting the strategy to the situation, and not choosing a one-size-fits-all approach
    • Allowing myself to refactor tests (to fix such test smells)
    • Trying different organization styles

    Part of the reason of the Fowler Signature Series' success I believe comes in its organization.  While the length of xUnit Test Patterns seems daunting at first (833 pages!), it's actually composed of two books.  This is what Martin Fowler refers to as a Duplex Book.

    The first part consists of a set of narratives and tutorials, and makes up less than 200 pages.  The rest of the book focuses on patterns and reference material.  The first part can be read straight through, while the second can be referred to as needed.  While I carefully read the first section, it didn't take longer than a Saturday afternoon to get through.  The rest of the book I'll probably get to as I come up against specific situations and smells.

    For those that are:

    • New to unit testing
    • Old pros to unit testing
    • Completely oblivious to unit testing

    You'd do yourself (and your team and employer) a great service by giving xUnit Test Patterns a go.  If you wind up hating it, well, it's big enough to make a fantastic door stop.

    Posted Mar 16 2008, 10:15 PM by bogardj with 6 comment(s)
    Filed under:
  • Clearing up the Mock confusion

    There's some bad blood concerning Mocks, and a lot of it rightfully so.  Because of popular mocking frameworks, the name "Mock" has become interchangeable for "Test Double".  In Texas, we ask for a Kleenex, not a tissue, and a Coke instead of a soft drink.  The brand name has defined the family of products, though not every soft drink is a Coke.

    Because of the Mock/Test Double confusion, Mocks are used in many wrong places, where another Test Double is more appropriate.  For the record:

    A Test Double is a general term for a test-specific substitute.  Mocks, among others, are a specific type of Test Double.

    If you look through your tests and all you see are Mock Objects, chances are pretty good you'll have some very brittle tests that are coupled tightly to the implementation of the class under test.  Specific types of Test Doubles include:

    • Test Stub
    • Test Spy
    • Mock Object
    • Fake Object
    • Dummy Object

    A Test Stub is used to control the indirect inputs of a class under test.  By setting up different values for the Test Stub, we can force our class under test down specific paths.

    A Test Spy is used to capture the indirect outputs of a class under test.  By capturing the indirect outputs, we can verify messages being sent by the class under test that we might not have access to otherwise.  Test Stubs and Test Spies can be combined to force inputs and verify outputs.

    A Mock Object is used to verify the interactions between a class under test and the Mock Object.  Mock Objects verify interactions usually by incorporating Record and Replay modes, where all method calls made in the Replay mode must be set up in the Record mode.  Strict Mock Objects are useful for ensuring that only the methods specified are called, and nothing more.  Loose Mock Objects are useful for ensuring that specified methods are called, but extra methods called won't cause errors.

    A Fake Object is used to substitute a simpler implementation for an otherwise complex or lengthy behavior.  Typically this could mean an in-memory database instead of the real thing, which provides all the functionality of the real database, but only for the lifetime of the test.  For example, instead of a CustomerRepository hitting the database, the Fake Object might just use local collection objects.

    A Dummy Object is used to fill a parameter for a method.  Similar to Test Stubs, except no verification is done, and they're not used to drive specific paths.  As the name implies, Dummy Objects are used just so the code can compile and run.

    As you can see from the description of the Mock Object, it tests a very specific scenario, interactions.  Using Mock Objects in place of all the others would lead to some serious issues.  Test what you mean to test, use the right Test Double for your situation, and you should come out fine in the end.

    Posted Mar 13 2008, 09:57 PM by bogardj with 4 comment(s)
    Filed under:
  • Advanced mocking: mocks and stubs

    Test Spies can help us verify the indirect outputs of a system under test.  If an OrderProcessor needs to send an email, we don't want that test sending real emails, so we set up a Test Spy to capture that indirect output so we can verify it inside our test.

    Sometimes a Test Spy isn't enough, as our test might have indirect inputs as well as indirect outputs.  An indirect input is an input variable or value that a method uses that doesn't appear in any object passed in to the method.

    In the previous Test Spy example, our business partners requested that an email be sent out for each order processed.  That was yesterday, and today, they have another request.  Sometimes, orders are sufficiently large that they would like a sales agent to also be notified by email, so that they might follow up with that customer and try to wring some more sales out of the customer's pockets.

    Two conditions arise: the order maximum might change, and it might depend on the customer placing the order.  After some more conversation, it turns out that the logic behind whether an Order should be emailed to a Sales Rep or not is fairly complex.

    So instead of embedded this complex logic inside our order processor, we'll extract it into a Specification:

    public interface ISpecification<T>
    {
        bool IsSatisfiedBy(T value);
    }
    

    That Specification provides the indirect input that necessitates using a full-blown Mock Object.

    Examining the class under test

    With a Mock Object, we want to test both indirect inputs and outputs.  To do this, we can modify our original Test Spy to capture the input and provide a canned output.  To put this all in context, let's take a look at our OrderProcessor:

    public class OrderFulfillmentService
    {
        private readonly IMailSender _mailSender;
        private readonly ISpecification<Order> _salesSpec;
    
        public OrderFulfillmentService(IMailSender mailSender, ISpecification<Order> salesSpec)
        {
            _mailSender = mailSender;
            _salesSpec = salesSpec;
        }
    
        public void ProcessOrder(Order order)
        {
            // hit database, whatever
    
            //send email
            if (_salesSpec.IsSatisfiedBy(order))
            {
                string body = "Huge frickin' order alert!!!\r\nOrder #:" + order.OrderNumber;
    
                MailMessage message =
                    new MailMessage("sender@email.com", "salesdude@email.com",
                                    "Order processed", body);
    
                _mailSender.SendMessage(message);
            }
    
        }
    }
    

    When the Order satisfies the SalesSpec, the OrderProcessor should send an email to our Sales Rep.  Normally, I'd write the tests before modifying the class under test, but it's a little easier to see the scope of the change after it's already made.

    Here come the mocks!

    As with all Test Doubles, we have a motivation to supply an imposter dependency to our class under test.  In this case, the real IMailSender will send emails (which we don't want) and the real ISpecification has complicated logic (which we want to keep separate).

    For the ISpecification, not only do I want to test the indirect outputs (the Order passed in), but I want to verify the behavior of the system from its indirect outputs.  Going back to the original context and specification, "When the Order satisfies the SalesSpecification, it should send an email to the SalesRep".  Note the "should" part, we want to make sure that the IMailSender was actually called.

    The manual way

    When we care that the interaction between two components, we capture both the messages going back and forth and the number of times the interaction was used.  Our IMailSender mock will capture these two pieces of information and expose them for examination later:

    public class MailSenderMock : IMailSender
    {
        public MailMessage Message = null;
        public int SendMessageCallCount = 0;
    
        public void SendMessage(MailMessage message)
        {
            Message = message;
            SendMessageCallCount++;
        }
    }
    

    Looking at the ISpecification, I'm only verifying the interaction between the OrderProcessor and the IMailSender, so I'll just hard-code a specific result into a Test Stub:

    public class OrderSpecificationStub : ISpecification<Order>
    {
        private readonly bool _result;
    
        public OrderSpecificationStub(bool result)
        {
            _result = result;
        }
        
        public bool IsSatisfiedBy(Order value)
        {
            return _result;
        }
    }
    

    Note that I always give very intentional names to my Test Doubles.  Folks coming back and looking at my tests should be able to understand what I'm testing by the name of my fixtures, test methods, and variable names.  It never hurts to be as explicit and clear as possible.

    With these two Test Doubles in place, I'm ready to create my test:

    [Test]
    public void Should_send_sales_email_when_order_satisfies_sales_spec_manually()
    {
        bool result = true;
        MailSenderMock mailSenderMock = new MailSenderMock();
        OrderSpecificationStub orderSpecStub = new OrderSpecificationStub(result);
    
        OrderFulfillmentService service = 
            new OrderFulfillmentService(mailSenderMock, orderSpecStub);
    
        Order order = new Order();
        order.OrderNumber = "8574-PO8468371";
    
        service.ProcessOrder(order);
    
        MailMessage message = mailSenderMock.Message;
    
        //Verify expectations
        Assert.AreEqual(1, mailSenderMock.SendMessageCallCount);
    
        //Verify outputs
        Assert.IsNotNull(message);
        Assert.AreEqual("sender@email.com", message.From.Address);
        Assert.AreEqual(1, message.To.Count);
        Assert.AreEqual("salesdude@email.com", message.To[0].Address);
        StringAssert.Contains(order.OrderNumber, message.Body);
    }
    

    I test both the expectations (the number of times the method was called) as well as the indirect outputs (the MailMessage).  With this test, I know with absolute certainty that when the Order satisfies the SalesSpecification, the MailSender is used to send an email to the sales rep.

    When this test passes, I'll create an additional test to cover the scenario where the Order doesn't meet the SalesSpec specification.  In that case, I'll just make sure that the SendMessageCallCount is zero and be done.

    Again, all these little classes can get annoying to maintain over time.  Although they're very explicit in their scope, if each fixture has 3-5 TestDouble implementations, they can really add up when your tests get into the thousands.

    Enter Rhino Mocks

    With Rhino Mocks, I can create both Test Stubs and Mocks.  It's pretty important to understand the different types of Test Doubles before jumping into a tool like Rhino Mocks, as excessive Mock Objects can lead to very brittle tests.  I rarely create more than one Mock Object in a single test, although I might have several different Test Doubles going on.

    Although the name is deceiving, Rhino Mocks can create all sorts of Test Doubles, including Test Stubs and Mock Objects (obviously).  With Rhino Mocks:

    [Test]
    public void Should_send_sales_email_when_order_satisfies_sales_spec()
    {
        MockRepository mocks = new MockRepository();
        ISpecification<Order> salesSpec = mocks.Stub<ISpecification<Order>>();
        IMailSender sender = mocks.CreateMock<IMailSender>();
    
        MailMessage message = null;
    
        Order order = new Order();
        order.OrderNumber = "8574-PO8468371";
    
        using (mocks.Record())
        {
            SetupResult.For(salesSpec.IsSatisfiedBy(order)).Return(true);
    
            sender.SendMessage(null);
    
            LastCall
                .IgnoreArguments()
                .Do(new Action<MailMessage>(actual => message = actual));
        }
    
        OrderFulfillmentService service = new OrderFulfillmentService(sender, salesSpec);
    
        service.ProcessOrder(order);
    
        mocks.VerifyAll();
    
        Assert.IsNotNull(message);
        Assert.AreEqual("sender@email.com", message.From.Address);
        Assert.AreEqual(1, message.To.Count);
        Assert.AreEqual("salesdude@email.com", message.To[0].Address);
        StringAssert.Contains(order.OrderNumber, message.Body);
    }

    In the first part, I create the Stub using the Stub<T> method on the MockRespository.  The Rhino Mocks stubs are nice as they provide out-of-the box property implementation.  Next, I create the Mock Object using the CreateMock method.  This creates the proxy class that will intercept my calls for verification later.  It performs much of the same functionality of my manually created Mock Object, but much more flexible.

    In the Record section (mocks.Record() part), I set up all of the results and expectations of my Test Doubles:

    • Setup a result for the Test Stub
    • Set up an expectation for the Mock Object
    • Capture the input of the Mock Object (the indirect output of the OrderProcessor)

    In the exercise portion, I create the OrderProcessor and pass in the Test Double implementations from Rhino Mocks.  To get the ball rolling, I call the ProcessOrder method, and I'm ready to start verifying.

    Finally, in the verification section, I first call the VerifyAll method on the MockRepository.  This call verifies all the expectations have been met, such as all methods were called that I set up, and no extra ones were called that I didn't set up.  I finish up the verification by performing assertions on the indirect output MailMessage I captured earlier.

    Small sidenote on expectations and verifications

    When using Mock Objects, your tests have a distinct pattern to them:

    • Set expectations
    • Verify expectations

    In the first section, I set up all the results and method call expectations I expect to be called when exercising the class under test.  In the verification section, Rhino Mocks examines the expectations versus what actually happened, and fails my test if it doesn't match up.

    So why not use the real implementations?

    Most of the backlash against Mock Objects is misdirected against Test Doubles.  Test Doubles are absolutely vital in narrowing the scope of failures when something goes wrong.  If a test fails but it calls into a hierarchy of a dozen components, how much time do I waste in trying to hunt down the real cause of failure?  More than 30 seconds figuring out a test failure is too long.

    Mock Objects can be too powerful and overkill in most situations.  If my test fails because something was called and I didn't set up the expectation, this tends to lead to tests that exactly match implementations.  That's a test smell of an over-specified test.  While tests are supposed to make it easy to change code, if a removing a method call causes an entire fixture and a dozen tests to fail, I haven't really gained anything.

    The trick is to know the different types of Test Doubles out there, and test what you mean to test.  Accidental verifications and assertions by making every Test Double a Mock Object leads to brittleness.  Pick the right Test Double for the situation, and your tests will be giving you the value they're supposed to.

    Posted Mar 12 2008, 10:16 PM by bogardj with 5 comment(s)
    Filed under:
  • A small correction

    During a conversation at this week's ADNUG, I realized the title of one of my latest posts (Advanced mocking: auto-interaction testing) had a misleading title.

    I was trying to be clever with the Greek "auto" meaning "self", so it was really about "self-interaction testing", not automatic-interaction testing, auto-mocking containers or anything like that.

    Every time I try to be clever...

    Posted Mar 11 2008, 07:52 AM by bogardj with no comments
    Filed under:
  • The many faces of ExpectedException

    I'm not a fan of the style most xUnit frameworks suggest for verifying exceptions.  After seeing the problems with using an attribute to perform assertions, many frameworks have come up with their own way of their own way of doing it.  Outside using a different xUnit framework, you can also perform this verification manually inside your test.  It's not quite as explicit, but it's possible.

    Suppose we have the following OrderProcessor that we'd like to test:

    public class OrderProcessor
    {
        private readonly INotificationService _notificationService;
    
        public OrderProcessor(INotificationService notificationService)
        {
            if (notificationService == null)
                throw new ArgumentNullException("notificationService");
    
            _notificationService = notificationService;
        }
    
        public void ProcessOrder(Order order)
        {
            if (order == null)
                throw new ArgumentNullException("order");
        }
    }
    

    Note that the same exception type is thrown from two different locations.  What I'd like to do is create a test specify some behavior that when ProcessOrder is called, it errors when the Order is null.  There are several ways of doing this, some that work better than others.

    Using attributes

    To set an expectation that a block of code will throw a certain type of exception, you need to decorate your test method with an ExpectedException attribute.  Both NUnit, MSTest, and MbUnit provide this attribute (all with the same name).  For example, here's an NUnit test verifying the exception test:

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Should_throw_ArgumentNullException_when_the_Order_is_null()
    {
        OrderProcessor processor = new OrderProcessor(null);
    
        processor.ProcessOrder(null);
    }
    

    This test passes, but for the wrong reason.  When I pass in the null argument for the OrderProcessor constructor, the constructor throws the exception, and the ProcessOrder method is never even executed!  This tests passes, but only accidentally.

    Additionally, it's not clear from the body of the test what specifically is supposed to fail.  As long as anything inside the method body throws the correct exception, the test will pass.  I don't like tests passing accidentally and I don't like opaque tests.

    Although NUnit's ExpectedException attribute has additional parameters for checking messages, etc., it's still a kludge around the real problem of using an attribute to perform assertions.

    Manual checking

    This is my preferred method when using NUnit, MSTest or MbUnit.  In this style, I put a try-catch block explicitly around the statement of code I expect to throw the exception.  Using NUnit:

    [Test]
    public void Should_throw_ArgumentNullException_when_the_Order_is_null()
    {
        OrderProcessor processor = new OrderProcessor(null);
    
        try
        {
            processor.ProcessOrder(null);
            Assert.Fail("Should throw ArgumentNullException");
        }
        catch (ArgumentNullException)
        {
        }
    }
    

    If the test code gets past ProcessOrder, I force a test failure (and provide a meaningful message).  This test now fails, as the constructor is the statement throwing the exception.  I get a fast, meaningful failure when ProcessOrder does not throw the expected exception.

    I test a specific exception type by only including that exception in the catch block.  If some other exception is thrown, the exception won't get caught by my specific catch block, and the test will fail.

    There are several variations of the manual checking, but the basic idea is the same.  Put a try-catch block only around the statement that should throw, and put in specific checking to make sure the test passes only when the exception you want is thrown.

    xUnit.net style - Assert.Throws

    Instead of using an attribute or doing manual try-catch blocks, xUnit.net introduces an Assert.Throws method, where I can supply behavior through a delegate.  This is all a mouthful, it's easier to see the code:

    [Fact]
    public void Should_throw_ArgumentNullException_when_the_Order_is_null()
    {
        OrderProcessor processor = new OrderProcessor(new NotificationService());
    
        Assert.Throws<ArgumentNullException>(() => processor.ProcessOrder(null));
    }
    

    I supply the block that should throw in the lambda expression, but this could be an anonymous delegate or function name.

    I really like this style as it combines the assertion, the exception type, and the block that throws into one readable statement.  Although the parameter-less lambda block can look strange, I'm able to confine the block that expects the exception to the one statement that should throw, just like I was able to do in the manual example.

    Looking at the source code behind the xUnit.net implementation, behind the scenes it does something very similar to the manual example.  It just wraps it up into one nice, neat call.

    NBehave style - fluent interface

    As we're pushing towards the 0.4 release of NBehave, we're trying more fluent syntax using BDD-style extension methods that wrap existing xUnit implementations.  For example, a fluent wrapper over MSTest would now look like:

    [TestMethod]
    public void Should_throw_ArgumentNullException_when_the_Order_is_null()
    {
        OrderProcessor processor = new OrderProcessor(new NotificationService());
    
        processor.WhenCalling(x => x.ProcessOrder(null)).ShouldThrow<ArgumentNullException>();
    }
    

    In the earlier example using lambdas, I was forced to use a parameter-less lambda that looked a little strange.  In this case, the specification is meant to be as human-readable as possible, almost sentence-like.  With some generics work, the lambda gets strongly typed to the class under test, so I get all of the IntelliSense and refactoring goodness.  (I'm still trying to reverse the order of the methods...not as simple as it seems.)

    So many choices...

    When it comes down to it, you want a test that:

    • Fails for the reasons you want
    • Can be immediately understood on what it's testing

    Whichever choice you go with, as long as it conforms to the above criteria, you should come out fine in the end.  For me, the attribute method is the only one that doesn't achieve either of the above.  Exceptions seem to have been made a special case, but since lambdas have made anonymous delegates much easier to deal with, better alternatives exist for the verbose or broken mechanisms we had to use previously.

    Posted Mar 10 2008, 10:25 PM by bogardj with 4 comment(s)
    Filed under:
  • Advanced mocking: anonymous test spy

    When practicing TDD, I create interfaces to abstract away the ugly stuff, like databases, file I/O, web service calls, email messages, and other external systems.  I can run tests now that don't have to interact with real implementations of these external components, which may or may not be available all the time or may take a long time to run in practice.

    But when testing a class that uses these components, I often want to verify messages or objects passed to these fake components.  Unfortunately, these messages are created internally in the method, and I don't have a way to access them directly.  For example, consider the OrderFulfillmentService, which needs to send emails when orders are fulfilled:

    public class OrderFulfillmentService
    {
        private readonly IMailSender _mailSender;
    
        public OrderFulfillmentService(IMailSender mailSender)
        {
            _mailSender = mailSender;
        }
    
        public void ProcessOrder(Order order)
        {
            // hit database, whatever
    
            //send email
            string body = "Your order is ready!\r\nOrder #:" + order.OrderNumber;
    
            MailMessage message =
                new MailMessage("sender@email.com", "recipient@email.com",
                                "Order processed", body);
    
            _mailSender.SendMessage(message);
        }
    }
    

    What I'd like to do is verify the MailMessage being sent to the IMailSender has the correct sender and recipient email addresses, and maybe that the body contains the OrderNumber.  But the creation of the MailMessage is internal to the method, and I really don't feel like extracting all of that out to a different public method or class if I don't need to.

    All I really care about is that when the OrderFulfillmentService processes an order, the correct email gets sent out.  If I extract the email creation to a separate class, I still have to write additional tests to ensure that the correct email message gets sent out, so I'm not that much better off going that route.

    If I could somehow intercept or catch the message being sent to the IMailSender in a test, I could verify its contents.  That's where the Test Spy pattern can help out.  Both with and without Rhino Mocks, I can intercept this indirect output.

    Here come the mocks!

    Since we don't want real emails being sent out during testing, we'll create a test double to stand in the IMailSender's place.  But the test double we use will be special, as we want to create a test to check the contents of the indirect outputs of the MailMessage.

    To do this, we'll create a Test Spy that snags the MailMessage and sticks the result into a local field that we can look at later in the test:

    public class MailSenderTestSpy : IMailSender
    {
        public MailMessage Message = null;
    
        public void SendMessage(MailMessage message)
        {
            Message = message;
        }
    }
    

    Pretty simple little class, I just stick whatever gets passed in to a local field.  So what will the test look like?  Here's what I came up with:

    [Test]
    public void Should_create_order_details_email_manually()
    {
        MailSenderTestSpy sender = new MailSenderTestSpy();
        OrderFulfillmentService service = new OrderFulfillmentService(sender);
    
        Order order = new Order();
        order.OrderNumber = "8574-PO8468371";
    
        service.ProcessOrder(order);
    
        MailMessage message = sender.Message;
    
        Assert.IsNotNull(message);
        Assert.AreEqual("sender@email.com", message.From.Address);
        Assert.AreEqual(1, message.To.Count);
        Assert.AreEqual("recipient@email.com", message.To[0].Address);
        StringAssert.Contains(order.OrderNumber, message.Body);
    }
    

    The setup of the OrderFulfillmentService is normal, except I pass in an instance of my test spy (soooo sneaky).  After calling the ProcessOrder method, I grab out the MailMessage.  Finally, I verify the contents of the MailMessage according to the customer's specifications.

    Creating the Test Spy manually is all well and good, so how might we create one in Rhino Mocks?

    Enter Rhino Mocks

    In most mocking scenarios, I set expectations that methods will get called, and later verify these expectations.  In the Test Spy case, I not only want to set expectation that the method will get called, but I want to additionally grab the MailMessage when the mock gets called.  Luckily, I can supply extra behavior with the Do() method in Rhino Mocks.  Let's take a look at the test:

    [Test]
    public void Should_create_order_details_email()
    {
        MockRepository mocks = new MockRepository();
        IMailSender sender = mocks.CreateMock<IMailSender>();
    
        MailMessage message = null;
    
        using (mocks.Record())
        {
            sender.SendMessage(null);
    
            LastCall
                .IgnoreArguments()
                .Do(new Action<MailMessage>(actual => message = actual));
        }
    
        OrderFulfillmentService service = new OrderFulfillmentService(sender);
    
        Order order = new Order();
        order.OrderNumber = "8574-PO8468371";
    
        service.ProcessOrder(order);
    
        mocks.VerifyAll();
    
        Assert.IsNotNull(message);
        Assert.AreEqual("sender@email.com", message.From.Address);
        Assert.AreEqual(1, message.To.Count);
        Assert.AreEqual("recipient@email.com", message.To[0].Address);
        StringAssert.Contains(order.OrderNumber, message.Body);
    }
    

    Instead of creating my custom little Test Spy class, I use RhinoMocks and the CreateMock method to create a mock implementation of the IMailSender.  Rhino Mocks creates an implementation at runtime, so I never have to worry about managing this extra test double class.

    In the Record phase, I call the SendMessage method on the IMailSender, but I pass in null.  This looks strange, don't I actually want something sent in?  In normal mocking scenarios where I'm verifying the arguments, I would pass the real arguments I expect would be used by the class under test.  But since the MailMessage is created inside the ProcessOrder method, I don't know what the MailMessage is.

    In the next part, I use LastCall to get at the last method call to a mock object (in this case the SendMessage) and start applying expectations and options.  I IgnoreArguments, as I don't want Rhino Mocks to care about the null that was passed in.  That's why the null doesn't matter, I explicitly tell Rhino Mocks not to care.  Finally, I use the Do method to supply a custom Action<MailMessage>, giving it a lambda expression that creates a closure and captures the MailMessage that got passed in.

    Quick sidenote on the magic

    Yes, I know that was a mouthful, but the basic idea is I want to create a Delegate object that matches the signature of the method I just called (SendMessage).  The signature of this method is:

    void SendMessage(MailMessage message);

    Since Rhino Mocks expects an instance of a Delegate object (and not just any old delegate), I can't pass in the lambda directly.  Instead, I have to create an instance of a delegate type and pass that in.  I can create a delegate type directly:

    public delegate void SendMessageDelegate(MailMessage message);

    But instead, I'll use the built-in generic delegates (Action<T>) that match my method.  For void methods, I use the Action delegates, and for methods that return values, I use the Func delegates.

    Finally, I create the lambda expression (I could have used an anonymous delegate, or just the name of a local method that matches that signagture).  This is a special lambda expression that has access to the local scope, so I can snag the MailMessage sent in to the lambda and set it to a local variable (this is the closure part).

    Back to the test

    Skipping past the first part, we can see from the OrderFulfillmentService instantiation on down, the test looks much of the same as the first one.  The lamdba part can be strange to look at the first time, but it's a succinct way to pass in a custom snippet of behavior.  When the SendMessage method gets called by the ProcessOrder method, Rhino Mocks will route that call to the lambda expression I gave it.  This lambda expression takes the MailMessage passed in and assigns it to a local variable.

    I finish up the test by checking the MailMessage contents, and the test passes just as well as the first example.  This time, no extra test spy class hangs around.

    Wrapping it up

    Test spys are great for capture indirect outputs of operations.  The MailMessage created above couldn't be observed directly as I didn't return it out of the method, so I had to create a special class to snag the MailMessage that got passed in.  Later, I could examine the MailMessage capture and verify its contents to my hearts desire.

    I did this with both a custom Test Spy class and with Rhino Mocks.  Use whatever one is most clear to the reader of the test, but Rhino Mocks can be helpful in reducing the number of test double classes that can pile up.  Since each test in one fixture might use a different kind of test double, using Rhino Mocks eliminates the extra overhead of the test double implementations.

    Posted Mar 06 2008, 10:43 PM by bogardj with 24 comment(s)
    Filed under: ,
  • Advanced mocking: auto-interaction testing

    When dealing with legacy systems or those not designed with specific testability scenarios in mind, you have to test your changes in non-traditional means.  In normal mocking (or test double) scenarios, you have some kind of external dependency that you want to substitute for.

    For example, you might have a OrderProcessingService that needs to send an email out when an order is completed.  During testing, you don't want actual emails being sent out, so you hide email sending behind an IMailSender interface, and use an imposter in its place.

    But what happens when you're working in a legacy system, or the difficult component you're dependent upon is the class you're testing?  These scenarios are common when modifying legacy code, or you're extending a third-party component or library.  In these cases, I need to verify interactions of the class with itself, leading to auto-interaction tests.

    Modifications needed

    We're trying to extend an order processing system that was built several years ago, and has absolutely zero unit tests.  The business has come with a request to introduce discounts to orders, and need the total to reflect the order.

    To make this change, we need to create a DiscountPercentage property on the Order object, and call the UpdateTotal method when the DiscountPercentage is set:

    public class Order
    {
        private int _discountPercentage;
    
        public virtual void UpdateTotal()
        {
            //hit database, tax service, etc.
        }
    
        public int DiscountPercentage
        {
            get { return _discountPercentage; }
            set
            {
                 _discountPercentage = value;
                UpdateTotal();
            }
        }
    }

    Now, for whatever reason, this is the exact change we have to make.  The UpdateTotal method must be called in this architecture to update the OrderTotal on the Order object.  Our resident system experts tell us that UpdateTotal must be called any time changes are made that could affect the OrderTotal.

    Not the best architecture, but in legacy systems, we have to work with what's given us.  So where does the mocking come into play?

    Here come the mocks!

    When we want to test the DiscountPercentage that calls the UpdateTotal method, we wind up hitting the database, the tax web service, maybe even a sherpa in Nepal.  We could try to fake out all of these dependencies, but nothing in our Order object is built to do this.  Additionally, there are many other places in our system that are in dire need of refactoring, so we can't commit resources to "fix" the Order class.

    Our resident system expert has assured us however, that all we need to care about is that the UpdateTotal method is called, the DiscountPercentage property will work.  So what I'd like to do is create a test that sets the DiscountPercentage, and just makes sure that the UpdateTotal method is called.  I don't want the real UpdateTotal method actually do its work, as it hits the database and whatnot, but just to verify that the method is called.

    The manual way

    First, I'll try and do this without a mocking framework like Rhino Mocks.  To do so, I'll create a test-specific subclass of the Order object:

    public class TestOrder : Order
    {
        public bool UpdateTotalCalled = false;
    
        public override void UpdateTotal()
        {
            UpdateTotalCalled = true;
        }
    }
    

    I override the method interaction I'm interested in, "UpdateTotal", and set a flag that simply checks to see if it was called.  I also made sure I didn't cal