I am trying to use AutoFixture to simplify my life.
How do I mock a class with
- non-public constructor and
- non-public Id and
- static 'Create' method?
Example
public class User
{
private User(){}
/// <summary>
/// Created by Database...
/// </summary>
public long? Id { get; protected set; }
public string Name { get; protected set; }
public static User Create(string name)
{
var user = new User {Name = name};
return user;
}
}
I've tried using a combo of Factory and SpecimenBuilder:
[Fact]
public void CreatingUserWithId_Should_Work_UsingFactoryAndSpecimenBuilder()
{
IFixture fixture = new Fixture().Customize(new AutoFakeItEasyCustomization());
fixture.Customizations.Add(new UserBuilder());
fixture.Customize<User>(o => o.FromFactory(() => User.Create("foo")));
var user = fixture.Create<User>();
user.Should().NotBeNull();
user.Id.Should().HaveValue();
}
with
public class UserBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var pi = request as PropertyInfo;
if (pi == null) return new NoSpecimen(request);
// The following code only works for public properties... :-(
if (pi.Name == "Id" && pi.PropertyType == typeof (long?)) return 42;
return new NoSpecimen(request);
}
}
A demo C# solution is available at https://github.com/draptik/MockingStaticCreate
Thankful for any pointers,
Patrick