8

We have an enum:

enum Letters
{
    A,
    B,
    C,
    D,
    E        
}

When I try:

var frozenLetter = fixture.Freeze(Letters.D);

Strangely, frozenLetter == A.

var letter = fixture.Create<Letters>();
var anotherLetter = fixture.Create<Letters>();

Letter and anotherLetter both equal A, so the Letters type has been frozen, but to the first constant in the enum rather than the one specified.

Is there a way to freeze an enum to the constant I wish?

jcorcoran
  • 253
  • 1
  • 9
  • I might be missing something, but what does the Freeze method do? – ppalms Feb 06 '14 at 18:35
  • 1
    It "freezes" the type so that it always returns the same instance whenever an instance of that type is requested. See [AutoFixture Freeze](http://blog.ploeh.dk/2010/03/17/AutoFixtureFreeze/) by Mark Seeman, AutoFixture's author. – jcorcoran Feb 06 '14 at 18:40
  • 1
    Hm, looks like [enums are not supported](http://autofixture.codeplex.com/workitem/1744) by AutoFixture. As a workaround you could declare a constant (`private const Letters constLetter = Letters.D;`) at the top of your class and use that instead of creating enums with AutoFixture. – Pierre-Luc Pineault Feb 06 '14 at 18:47
  • 3
    They are now: see [EnumGenerator.cs](https://github.com/AutoFixture/AutoFixture/blob/master/Src/AutoFixture/EnumGenerator.cs). That would be a simple work-around but an instance of Letters is created indirectly a nested value of other types. – jcorcoran Feb 06 '14 at 18:59
  • 2
    @Pierre-LucPineault Please note that the very resource you link to explicitly states that the issue was *fixed in July 2010!* – Mark Seemann Feb 06 '14 at 20:28

1 Answers1

8

Freeze Inject and Register are slightly different.

Use Inject for the described behavior, as the following test demonstrates:

[Fact]
public void Test()
{
    var fixture = new Fixture();

    var expected = Letters.D;
    fixture.Inject(expected);

    var letter = fixture.Create<Letters>();
    var anotherLetter = fixture.Create<Letters>();

    Assert.Equal(expected, letter);
    Assert.Equal(expected, anotherLetter);
}

The problem with the question's sample code is that the parameter (seed) isn't used as the frozen value.

Community
  • 1
  • 1
Nikos Baxevanis
  • 10,868
  • 2
  • 46
  • 80