nickdodd79 / AutoBogus

A C# library complementing the Bogus generator by adding auto creation and population capabilities.
MIT License
431 stars 50 forks source link

[Question] Autogenerating a struct containing argument guards #59

Closed Eric-Bonneau closed 3 years ago

Eric-Bonneau commented 3 years ago

Hi there,

I've ran into a bit of an issue where I'm using AutoBogus to generate a struct which has argument guards for its constructor.

I would new up an AutoFaker<T> and use a custom RuleFor with this property, but it seems a bit tedious. Is there a way to easily achieve what I'd like without having to duplicate a bunch of RuleFors?

For reference, here is a sample application containing the issue I'm experiencing:

class Program
{
    static void Main(string[] args)
    {
        // The line just below will sometimes work, and other times fail when I get MyEnum.None
        var generatedStruct = AutoFaker.Generate<MyStruct>(); 

        Console.Read();
    }
}

enum MyEnum
{
    None,
    Something
}

readonly struct MyStruct
{
    public MyEnum Something { get; }

    public string Value { get; }

    public MyStruct(MyEnum something, string value)
    {
        if (something == MyEnum.None)
        {
            throw new ArgumentException();
        }

        Something = something;
        Value = value;
    }
}

Thanks in advance :).

nickdodd79 commented 3 years ago

Hey @Eric-Bonneau

The best approach at the moment would be the override. When you create your Override code, there is a virtual method Preinitialize which you can use to control whether a value is generated before calling the override.

This details got missed off in the Readme, but should be there now.

Hope that helps.

Nick.

Eric-Bonneau commented 3 years ago

Hi @nickdodd79,

Thanks for the info. Will try this out!