Posts Tagged ‘test data builder’

Using Factories for testing Castle ActiveRecord: Part 3 : Test Data Builders

Wednesday, January 14th, 2009

I recently was trying to make a test data factory for Castle ActiveRecord like the Ruby on Rails plugin Machinist and posted about my results. Today, I read a post titled, Test Data Builders: an alternative to the Object Mother Pattern.
This is a little more work that the previous alternative of writing up a Blueprint file, but I liked the fluent nature of it, and it’s not all that hard to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
 
 
namespace Government.Models.Tests
{
    public class PersonBuilder
    {
        private string _firstName = Faker.NameFaker.FirstName();
        private string _lastName = Faker.NameFaker.LastName();
        private int _secretGovernmentId = Faker.NumberFaker.Number(11111111, 9999999999);
 
        public PersonBuilder WithFirstName(string firstName)
        {
            this._firstName = firstName;
            return this;
        }
 
        public PersonBuilder WithLastName(string lastName)
        {
            this._lastName = lastName;
            return this;
        }
 
        public PersonBuilder WithSecretGovernmentId(int govID)
        {
            this._secretGovernmentId = govID;
            return this;
        }
 
        // builds but doesn't save
        public Person Build()
        {
            return new Person(_secretGovernmentId, _firstName, _lastName);
        }
 
        // builds and then saves and flushes
        public Person Make()
        {
            Person person= new Person(_secretGovernmentId, _firstName, _lastName);
            ActiveRecordMediator<person>.SaveAndFlush(person);
            return ActiveRecordMediator<person>.FindByPrimaryKey(person.Id);
        }
 
    }
}

You can then call it with as many of the With clauses as you like and either save it to the DB or not.

1
2
3
4
5
6
7
8
9
// Make and save a random record
Person person = new PersonBuilder().Make();
// Make and save a record with First Name Bill and Secret Government ID of 123456789
Person person = new PersonBuilder().
                          WithFirstName("Bill").
                          WithSecretGovernmentID(123456789).
                          Make();
// Make a random record without saving
Person person = new PersonBuilder().Build();

That’s about all there is to it.