Should You Use Randomness in Unit Tests?
Asked by
DOWNSHIFT
I'm curious about the use of randomness in unit tests. Imagine you have a test that performs a specified number of operations—let's say 100. You want to ensure that the order of those operations doesn't affect the outcome (commutativity). To test this, you could run through the operations in their usual order and then again in a different order to see if it passes. However, the potential permutations of those operations are astronomical, making it impossible to test them all. Is it acceptable to randomly sample, perhaps 50 different permutations, to check if they all pass? I'd assume if random testing starts to fail, then at least one permutation will demonstrate a break in commutativity. Additionally, would logging the seed used for the random permutations help? Or is there a better approach for this kind of testing?
Answers
While Google has found success with fuzz testing, it's important to recognize that it complicates your unit testing strategy. You should make sure your tests are simple and readable. If you're using randomness, you need to be careful that it doesn't lead to overly complex tests that are hard to understand at a glance.
Reply to this answer
In my view, introducing randomness in unit tests is usually a red flag. If the process you're testing depends heavily on random values, it sounds like it could be restructured for better clarity. Random tests can also complicate debugging since you can't guarantee consistent results on successive runs.
Reply to this answer
I generally try to avoid randomness in unit tests altogether. The primary goal of unit tests is to assess specific units of code in isolation. Anything random can obscure the test's purpose. Instead, maybe use a set of fixed inputs that cover various edge cases.
Reply to this answer
I don't think random values should be a part of unit tests. Unit tests are meant to be predictable and repeatable. If a test fails, you want to be able to reliably debug it without worrying about unseen variables that randomness introduces. If you're worried about permutations, consider using property testing instead, which systematically checks the properties of a function rather than its random outputs.
Reply to this answer
In general, it's best to keep your unit tests deterministic. By using random inputs, you risk having tests that don't truly reflect the state of your code. It's much better to focus on a representative selection of test cases, including edge cases, rather than trying to cover every permutation.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions