nickdodd79 / AutoBogus

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

IPAddress default generation fails #50

Closed i2van closed 3 years ago

i2van commented 3 years ago

Error message: Specified argument was out of the range of valid values. (Parameter 'newAddress')

Looks like it calls IPAddress(long) constructor.

var ip = AutoFaker.Generate<IPAddress>();

Is there some kind of global callback to return generated IPAddress? I'm not interested in particular object/property (RuleFor), I'd like to generate fake IPAddress for all properties in hierarchy.

Note: IPAddress is a part of immutable object and passed to constructor.

yaniv120892 commented 3 years ago

Default implementation of AutoFaker when creating new instance of Type is defined in AutoBinder.cs

You can override this implementation and add yours by derive from AutoBinder, override CreateInstance method and define your implementation for specific object.

public class Program
    {
        static void Main()
        {
            AutoFaker.Configure(builder => { builder.WithBinder<MyBinder>(); });
            var ip = AutoFaker.Generate<IPAddress>();
            Console.WriteLine(ip);
       }
    }

public class MyBinder : AutoBinder
    {
        public override TType CreateInstance<TType>(AutoGenerateContext context)
        {
            if (context != null)
            {
                var type = typeof(TType);
                if (type == typeof(IPAddress))
                {
                    byte[] arr = { 1, 1, 1, 1 };
                    ConstructorInfo constructor = type.GetConstructor(new[] { typeof(byte[]) });
                    return (TType)constructor.Invoke(new object[] { arr });
                }
            }

            return base.CreateInstance<TType>(context);
        }
    }
i2van commented 3 years ago

@nickdodd79 I think it should be addressed by AutoBogus despite there is a workaround.

nickdodd79 commented 3 years ago

Hey @i2van

I have just released v2.12.0 which includes a generator for IPAddress.

Nick.