Unit test builder pattern

In the arrange section of the unit test an object, which is the subject of the unit test, is created. In most of the times this object has dependencies and a constructor with multiple parameters. This object is mostly created in multiple unit-tests ( the integration tests, system tests etc). A change to this object is causing a number of changes in the unit-tests. That is in most of the cases not convenient. Therefor it's handy to use the fluent builder pattern.

This is just the builder pattern as described on WikiPedia combined with fluent interface pattern allso on Wikipedia.

Example: the invoiceGeneratorBuilder object wich is returning an InvoiceGenerator object.

    public class InvoiceGeneratorBuilder
    {
        // privates
        private IStarlimsDataAccess starlimsDataAccess;
        private JobTypes jobType = JobTypes.Ubl;

        public InvoiceGeneratorBuilder WithDataAccess(IStarlimsDataAccess starlimsdataAccess)
        {
            starlimsDataAccess = starlimsdataAccess;
            return this;
        }

        public InvoiceGeneratorBuilder WithJobType(JobTypes jobtype)
        {
            jobType = jobtype;
            return this;
        }

        public InvoiceGenerator Build()
        {
            return new InvoiceGenerator(starlimsDataAccess, jobType);
        }
    }

And the change if the InvoiceGenerator object constructor is extended with a log object, which happens in real. The builder object has now a log method for passing in the log object, if desired, otherwise it uses a default. This is just a litle example of how the fluent builder pattern is preventing a log of changes in the unit tests.

    public class InvoiceGeneratorBuilder
    {
        // privates
        private IStarlimsDataAccess starlimsDataAccess;
        private JobTypes jobType = JobTypes.Ubl;
        private ILog logger = LogManager.GetLogger("unittest");

        public InvoiceGeneratorBuilder WithDataAccess(IStarlimsDataAccess starlimsdataAccess)
        {
            starlimsDataAccess = starlimsdataAccess;
            return this;
        }

        public InvoiceGeneratorBuilder WithJobType(JobTypes jobtype)
        {
            jobType = jobtype;
            return this;
        }

        public InvoiceGeneratorBuilder WithLogger(ILog log)
        {
            logger = log;
            return this;
        }

        public InvoiceGenerator Build()
        {
            return new InvoiceGenerator(starlimsDataAccess, jobType, logger);
        }
    }

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!