I like using the Builder pattern for building test data in unit tests. Builder pattern makes it clean if I need to build a valid object, in the unit tests, with the minimum required properties. It also makes it clear when I need to build an object and explicitly specify a different value for any of the properties.
Let’s say we have an entity class as followed
public class Article
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime PublishedDate { get; set; }
}
I would have a builder class in the unit test project as followed
public class ArticleBuilder
{
private Guid _id;
private string _title;
private string _content;
private DateTime _publishedDate;
public ArticleBuilder()
{
_id = Guid.NewGuid();
_title= "Test title";
_content= "Test content";
_publishedDate= DateTime.UtcNow;
}
public ArticleBuilder WithId(Guid id)
{
_id = id;
return this;
}
public ArticleBuilder WithTitle(string title)
{
_title = title;
return this;
}
public ArticleBuilder WithContent(string content)
{
_content = content;
return this;
}
public ArticleBuilder WithPublishedDate(DateTime publishedDate)
{
_publishedDate = publishedDate;
return this;
}
public Article Build() => new Article
{
Id = _id,
Title = _title,
Content = _content,
PublishedDate = _publishedDate
};
}
And this is how it’s used
// If I want the basic valid article
var simpleArticle = new ArticleBuilder().Build();
// If I want a different title
var articleWithDifferentTitle = new ArticleBuilder()
.WithTitle("This is a different title")
.Build();
// Or if I want to change all properties, I could chain them up
var test = new ArticleBuilder()
.WithTitle("Test sample article title")
.WithContent("This is a test article content")
.WithPublishedDate(DateTime.UtcNow.AddDays(10))
.Build();
