hakanaltindis
hakanaltindis

Reputation: 131

AutoFixture Create An Instance from An Interface Issue

My issue is, cannot create auto generated instance from the interface.

Here is my example:

public class SomeClass {
    public string TestName { get; set; }
}

// And then I call like this
var obj = new Fixture().Create<SomeClass>();

Concrete class is generated automatically and it's properties like this:

Console.WriteLine(obj.TestName);
// Output: TestNameb7c3f872-9286-419f-bb0a-c4b0194b6bc8

But I have an interface like below:

public interface ISomeInterface 
{
    string TestName { get; set; }
}

// And  then I call like this
var obj = new Fixture().Create<ISomeInterface >();

It is generated but it's properties is not set.

Console.WriteLine(obj.TestName);
// Output: null

How can I create an instance from the interface like the concrete class?

Upvotes: 1

Views: 3882

Answers (1)

Serhii Shushliapin
Serhii Shushliapin

Reputation: 2708

Agree with Mathew Watson comment, this question might already be answered in the mentioned question.

Just wanted to share my version which is slightly different from those answer from 2012 ;)

public interface ISomeInterface
{
    string TestName { get; set; }
}

public class SomeClass : ISomeInterface
{
    public string TestName { get; set; }
}

public class Test
{
    [Fact]
    public void Do()
    {
        var fixture = new Fixture();
        fixture.Customize<ISomeInterface>(x => x.FromFactory(() => new SomeClass()));
        var result = fixture.Create<ISomeInterface>();
        Console.Out.WriteLine("result = {0}", result.TestName);
        // output:
        // result = TestName2c7e6902-d959-46ce-a79f-bf933bcb5b7f
    }
}

Of course, AutoMoq or AutoNSubstitute are the options to consider.

Upvotes: 2

Related Questions