Replies: 1 comment 1 reply
-
Hey there, I ran into this very same issue when generating datasets for testing negative paths. I usually need something like "here's a set of valid keys, A, B, C, I need Bogus to generate me an valid key that's not A, B, or C". What I usually end up doing is probably not an optimal solution, but it's something like this: public static T? GenerateUnique<T>(
Func<T> generate,
HashSet<T> excludedItems,
int maxAttempts = 100)
{
var done = false;
T? result = default;
var attempt = 0;
do
{
attempt++;
var candidate = generate();
if (!excludedItems.Contains(candidate))
{
result = candidate;
done = true;
}
if (attempt >= maxAttempts)
{
done = true;
// you might even decide to throw an exception here
}
} while (!done);
return result;
}
// usage:
var realUserNames = new Set<string> { realUser.Name };
var fakeUser = new Faker<User>()
.RuleFor(c => c.FirstName, f => GenerateUnique(() => new Bogus.Person().FirstName, realUserNames))
.Generate(); I either get a unique item in at most Hope it helps! |
Beta Was this translation helpful? Give feedback.
-
I'm using the Faker library to obfuscate the private information of customers. My tests simply check that the real value is not the same as the obfuscated value. For faking things like first names and states, I'm looking for a way to generate a random value that's not the same as the current value. Right now I'm using
RuleFor
to make bogus instances and I'm hoping not to have to expand all my setter lambdas into multiple lines to run multiple checks to see if subsequent results are the same. If there's an easy way to do this, I'd appreciate the knowledge......would have to become:
Beta Was this translation helpful? Give feedback.
All reactions