AutoFixture picks the modest constructor (by default) and since userData
is not part of the modest constructor we need to customize two things here:
- Change the constructor strategy for a single type (FormsAuthenticationTicket).
- Supply a custom value to the
userData
constructor argument.
The following Customization encapsulates both:
internal class UserDataCustomization : ICustomization
{
private readonly string userData;
public UserDataCustomization(string userData)
{
this.userData = userData;
}
public void Customize(IFixture fixture)
{
fixture.Customize<FormsAuthenticationTicket>(c =>
c.FromFactory(
new MethodInvoker(
new GreedyConstructorQuery())));
fixture.Customizations.Add(new UserDataBuilder(this.userData));
}
private class UserDataBuilder : ISpecimenBuilder
{
private readonly string userData;
public UserDataBuilder(string userData)
{
this.userData = userData;
}
public object Create(object request, ISpecimenContext context)
{
var pi = request as ParameterInfo;
if (pi != null && pi.Name == "userData")
return this.userData;
return new NoSpecimen();
}
}
}
The following test passes:
[Fact]
public void UserDataIsCorrect()
{
var expected = "<foo></foo>";
var fixture = new Fixture();
fixture.Customize(new UserDataCustomization(expected));
var actual = fixture.Create<FormsAuthenticationTicket>();
Assert.Equal(expected, actual.UserData);
}
Hope that helps.
FWIW, here is also the same in F#:
open Ploeh.AutoFixture
open Ploeh.AutoFixture.Kernel
open System
open System.Reflection
open System.Web.Security
type UserDataCustomization (userData) =
let builder = {
new ISpecimenBuilder with
member this.Create(request, context) =
match request with
| :? ParameterInfo as pi
when pi.Name = "userData" -> box userData
| _ -> NoSpecimen request |> box }
interface ICustomization with
member this.Customize fixture =
fixture.Customize<FormsAuthenticationTicket>(fun c ->
c.FromFactory(
MethodInvoker(
GreedyConstructorQuery())) :> ISpecimenBuilder)
fixture.Customizations.Add builder
The following test passes:
open Xunit
open Swensen.Unquote.Assertions
[<Fact>]
let UserDataIsCorrect () =
let expected = "<foo></foo>"
let fixture = Fixture().Customize(UserDataCustomization(expected))
let actual = fixture.Create<FormsAuthenticationTicket>()
test <@ expected = actual.UserData @>