Search code examples
c#autofixture

Populating an object property with one of a limited set of characters using AutoFixture


I am using AutoFixture to generate a list of ProblemClass objects to be used for testing. ProblemClass is defined as

public class ProblemClass
{
    int Id {get; set;}
    string ProblemField {get; set;}
}

ProblemField can contain one of 3 values "A", "B" or "C". I can't change ProblemClass so I can't make ProblemField an enum.

How can I get AutoFixture to populate the ProblemField property of each object in my list randomly with an "A", "B", or "C"?

(e.g. myList[0].ProblemField is "A", myList[1].ProblemField is "C", etc.)

Thanks!


Solution

  • You can customize how the ProblemClass is generated.

    This should work:

    fixture
        .Customize<ProblemClass>(ob =>
            ob
                .With(
                    x => x.ProblemField,
                    (int i) => "ABC".Substring(i % 3, 1)));
    

    More info:

    From the cheatsheet

    Marks blog