Cleaner Code in Unit Tests

One thing that can quickly become messy when writing unit tests is the creation of test objects. If the test object is a simple int, string, etc then it's not as much of a problem as when you a list or object graph you need to create.

Even using object initializers you can end up taking a lot of lines of indented code, and gets in the way of the tests.

One solution is to use a 'builder' class which will construct the object for you.

For example, rather than lots of initializer code you could write:

            _sampleData = new HistoryBuilder()
                .WithTimer(false11new DateTime(200011))
                .WithTimer(false11new DateTime(200011))
                .WithTimer(true11new DateTime(200011))
                .Build()

 You can multiple overloads of WithTimer (for example one which create adds a default Timer).

 Implementation of HistoryBuilder:

    public class HistoryBuilder
    {
        private readonly History _history;
        public HistoryBuilder()
        {
            _history = new History();
        }
        public HistoryBuilder WithTimer()
        {
            _history.Timers.Add(new Timer());
            return this;
        }
        public HistoryBuilder WithTimer(bool completed, int internalInteruptions, int externalInteruptions,
                                        DateTime time)
        {
            _history.Timers.Add(new Timer
                                    {
                                        Completed = completed,
                                        InternalInteruptionsCount = internalInteruptions,
                                        ExternalInteruptionsCount = externalInteruptions,
                                        StartedTime = time
                                    });
            return this;
        }
        public History Build()
        {
            return _history;
        }
    }

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading