Freeze enum value in AutoFixture
Asked Answered
G

1

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?

Galegalea answered 6/2, 2014 at 18:31 Comment(5)
I might be missing something, but what does the Freeze method do?Lacework
It "freezes" the type so that it always returns the same instance whenever an instance of that type is requested. See AutoFixture Freeze by Mark Seeman, AutoFixture's author.Galegalea
Hm, looks like enums are not supported 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.Columbarium
They are now: see EnumGenerator.cs. That would be a simple work-around but an instance of Letters is created indirectly a nested value of other types.Galegalea
@Pierre-LucPineault Please note that the very resource you link to explicitly states that the issue was fixed in July 2010!Tollmann
S
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.

Sotted answered 6/2, 2014 at 20:20 Comment(1)
Aha, classic mistake there. Thanks for the clear explanation.Galegalea

© 2022 - 2024 — McMap. All rights reserved.