Søren M. Olesen
Søren M. Olesen

Reputation: 35

Autofixture, expected behavior?

Having a test similar to this:

public class myClass
{
    public int speed100index = 0;
    private List<int> values = new List<int> { 200 };

    public int Speed100
    {
        get
        {
            return values[speed100index];
        }
    }
}
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var fixture = new Fixture();
        var sut = fixture.Create<myClass>();
        Assert.AreEqual(sut.Speed100, 200);
    }
}

Would have expected this to work, but I can see why it's not. But how do I argue, that this is not a problem with AutoFixture, but a problem with the code?

Upvotes: 1

Views: 137

Answers (2)

Adam C
Adam C

Reputation: 451

AutoFixture is giving you feedback about the design of your class. The feedback is, you should follow a more object-oriented design for this class.

Protect your private state, to prevent your class from entering an inconsistent state.

You need to make the speed100index field, private, to ensure it remains consistent with the values List.

Upvotes: 1

trailmax
trailmax

Reputation: 35126

Here is what I see if I run debugger on your test:

Debugging

Autofixture assigns a random number to speed100index field because it is public, and in your array there is nothing at point 53 (from my screenshot)

If you set speed100index to be private, Autofixture will not re-assign the number and your test will pass.

Upvotes: 1

Related Questions