nickdodd79 / AutoBogus

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

AutoBogus.Moq does not work for get-only properties in interfaces #100

Open jcotton42 opened 1 year ago

jcotton42 commented 1 year ago

I was attempting to use AutoBogus.Moq to generate some fake data interfaces. Unfortunately the interfaces in question have get-only properties, which AutoBogus.Moq doesn't seem to support.

using AutoBogus;
using AutoBogus.Moq;

AutoFaker.Configure(builder => builder.WithBinder<MoqBinder>());

var autoGet = new AutoFaker<IGet>()
    .RuleFor(f => f.User, f => f.Random.Int())
    .RuleFor(f => f.Guild, f => f.Random.Int())
    .RuleFor(f => f.Channel, f => f.Random.Int())
    .Generate();

var autoGetSet = new AutoFaker<IGetSet>()
    .RuleFor(f => f.User, f => f.Random.Int())
    .RuleFor(f => f.Guild, f => f.Random.Int())
    .RuleFor(f => f.Channel, f => f.Random.Int())
    .Generate();

autoGet.Dump();
autoGetSet.Dump();

public interface IGet {
    int User { get; }
    int Guild { get; }
    int? Channel { get; }
}

public interface IGetSet {
    int User { get; set; }
    int Guild { get; set; }
    int? Channel { get; set; }
}

image

Is this reasonably doable? Or would the best solution for situations like mine be to create fakes manually using Moq and regular Bogus?

At the very least some sort of exception seems appropriate, the above code doesn't throw anything, despite the RuleFors have no effect when used on an IGet.

brunobertomeuskoon commented 1 year ago

I have the same issue, RuleFor doesn't have any effect because my classes only contain properties that are get-only, only initialized by the constructor:

var products = new AutoFaker<Product>()
    .RuleFor(p => p.ProductId, f => f.Random.Int(1))
    .Generate(3);

public class Product
{
    public Product(
        long productId,
        string productName)
    {
        ProductId = productId;
        ProductName = productName;
    }

    public long ProductId { get; }
    public string ProductName { get; }
}

It would be nice if AutoBogus could initialize the object automatically using constructor parameters if necessary.

EgoPingvina commented 6 months ago

It still can't do that. Any news?