Posts Tagged ‘Unit Testing’

Unit Testing And Factory Pattern

March 1, 2010 7 comments

I had a comment the other day on how a factory method / abstract factory object may increase coupling and not allow unit testing. Basically the idea was then to use dependency injection for the factory.

You do not have to do this you can use this technique I learnt from “The art of unit testing book” by Roy Osherove.

public static class TaxationCalculatorFactory

        private static ITaxationCalculator calculator = null;

        private static void InitializeForTest(ITaxationCalculator calc)
            calculator = calc;

        public static ITaxationCalculator GetCalculator(string location)

            if (calculator != null)
                return calculator;

            switch (location)
                case "Australia":
                    return new AustralianTaxCalculator();
                case "British":
                    return new BritishTaxCalculator();
                    throw new ArgumentException("Invalid Location");

    public interface ITaxationCalculator
        decimal CalculateTaxPayable(decimal salary);

Basically this would allow you to assign a mock / stub for the purpose of testing.