Search code examples
c#unit-testingobjectbuilder

With Method that takes Func<T> on an Object Builder


I am trying to create an Object Builder so I can easily create objects for unit testing. I would like to create a With() method so I can pass in a Func<> and it will set the correct property for me.

Here is what I have so far:

public class EquipmentModelBuilder
{

    public EquipmentModel Object { get; set; }

    public EquipmentModelBuilder()
    {
        Object = new EquipmentModel();
    }

    public EquipmentModelBuilder WithCategory(int categoryId)
    {
        Object.EquipmentCategoryID = categoryId;
        return this;
    }

    public EquipmentModelBuilder With(Func<EquipmentModel> setter)
    {
        Object = setter.Invoke();
        return this;
    }

    public EquipmentModel Build()
    {
        return Object;
    }
}

Of course, the WithCategory() works, but I don't want to create all the methods for each property, I would like to be able to:

EquipmentModelBuilder.With(x => x.Property1 = 1).With(x => x.Property2 = "2").Build()

Any idea what I am doing wrong?


Solution

  • You need to use an Action<EquipmentModel> as your argument rather than a Func<EquipmentModel>.

    public EquipmentModelBuilder With(Action<EquipmentModel> setter)
    {
        setter.Invoke(this.Object);
        return this;
    }