1

I am trying to use the library called FakeO (https://github.com/rally25rs/FakeO) It works fine except when there is a Guid property. Anyone have an idea what I maybe doing wrong ?

Exceptin I get is : Object of type 'System.Int32' cannot be converted to type 'System.Guid'.

here is the code

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Get a single instance of an object");
            var gud = Guid.NewGuid();

            var obj1 = FakeO.Create.Fake<SampleClass>(
                                                      s => s.UniqueId = FakeO.Data.Random<Guid>(),
                                                      s => s.Id = FakeO.Number.Next(),
                                                      s => s.PhoneNumber = FakeO.Phone.Number(),
                                                      s => s.SomeString = FakeO.String.Random(50));
            Console.WriteLine(obj1.ToString() + "\n");

            IEnumerable<SampleClass> obj2 = FakeO.Create.Fake<SampleClass>(10, s => s.Id = FakeO.Number.Next(),
                                                      s => s.PhoneNumber = FakeO.Phone.Number(),
                                                      s => s.SomeString = FakeO.String.Random(50));

            foreach (var obj in obj2)
                Console.WriteLine(obj.ToString());

            Console.ReadKey();
        }
    }

    public class SampleClass
    {
        public int Id { get; set; }
        public string SomeString { get; set; }
        public string PhoneNumber { get; set; }
        public Guid UniqueId { get; set; }

        public override string ToString()
        {
            var output = "ID={0},SomeString ={1},PhoneNumber = {2}";
            return String.Format(output, Id, SomeString, PhoneNumber);
        }
    }
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Perpetualcoder
  • 13,501
  • 9
  • 64
  • 99

2 Answers2

1

Guid is value type, and the author did not handle unsupported ValueType properly. He returns 0 for all unsupported value types in the Data.Random method, which is not quite nice for any struct type. According to this StackOverflow question, the last lines of Data.Random should be fixed to

if(t.IsValueType)
{
    return Activator.CreateInstance(t);
}
return null;

This will return default value for struct type, which is empty Guid in case of Guid type I believe. If you want to support Guid type, you can add it in Data.Random method just before the final check of ValueType:

if (t == typeof(Guid))
    return Guid.NewGuid();

I did not test my solution, but it should do.

Community
  • 1
  • 1
tia
  • 9,518
  • 1
  • 30
  • 44
1

It looks like you should be using:

FakeO.Distinct.Guid()
Chris Doggett
  • 19,959
  • 4
  • 61
  • 86