How to get AutoFixture create an integer that is >0, and not another number?
Asked Answered
B

1

17

I want AutoFixture to generate two integers, and for the second one, I don't want it to be 0, or the previous generated number. Is there a way to tell AutoFixture to honor that "requirement".

Looking at RandomNumericSequenceGenerator, I looks like the lower limit is 1, so I might not have to specify the first requirement. Next, I was looking at the "seeding" option, but as indicated in this answer, it won't be used for a number, by default.

Is there something I'm overlooking here?

Branle answered 25/9, 2015 at 11:18 Comment(7)
Do you use plain-AutoFixture or AutoFixture.Xunit/NUnit?Toliver
Unfortunately, plain AutoFixture using MSTest. Why? And how would Xunit help, for example?Branle
It's less boilerplate with AutoFixture.Xunit. See the answer below.Toliver
Why not just use the fixture.CreateMany(2) ? As i understand from the documentation link the second number will be always > 0 and not another number.Rhapsodic
Good catch! Yes, that's easier and works by default, as @MarkSeemann wrote. It should also be the accepted answer.Toliver
@Rhapsodic I was apparently overlooking something indeed ;) My question had the hidden assumption that AutoFixture didn't do that, but apparently it already does exactly what I want ^_^Branle
@Branle I asked it because i was also not sure. Anyway the problem is solved :)Rhapsodic
T
21

Here's a way to do this with plain AutoFixture:

[Fact]
public void GenerateTwoDistinctNonZeroIntegersWithAutoFixture()
{
    var fixture = new Fixture();
    var generator = fixture.Create<Generator<int>>();

    var numbers = generator.Where(x => x != 0).Distinct().Take(2);
    // -> 72, 117
}

And here's a way to do this with AutoFixture.Xunit:

[Theory, AutoData]
public void GenerateTwoDistinctNonZeroIntegersWithAutoFixtureXunit(
    Generator<int> generator)
{
    var numbers = generator.Where(x => x != 0).Distinct().Take(2);
    // -> 72, 117
}
Toliver answered 25/9, 2015 at 12:31 Comment(3)
This will work, but isn't the requested behaviour the default behaviour of AutoFixture?Valais
OMG, indeed. I was tricked when I first read the original question. This should be the answer, as commented by @AlexanderW. Good catch! Thank you for pointing that out.Toliver
@NikosBaxevanis You're right, and I've unaccepted your answer. I cannot accept Mark's comment, since it's a comment, of course. Maybe Mark can "promote" his comment, so I can accept it ;)Branle

© 2022 - 2024 — McMap. All rights reserved.