Imagine next situation: you have some third party API with some methods that hasn' t test environment. So you wrote custom test-service to simulate behaviour of third party API with test-implementations of methods. Third party API may throw exceptions or return response model with some success/failed statuses.
I wanna write test-service, which may be configured to throw exceptions based on total request/method invocations count N (which also increases with every request) and provided percentage probability to throw some exception.
For instance: if provided 10% then it means that method should throw exception with 10% percent probabilty.
Question: is there some kind of math formula to solve this problem ?
If represent it it code I want to write something like this
boolean shouldThrow(int probabilityPercentage, long currentTotalExecutionsCount) {
return // and here this magic math formula to make a decision
}
Based on the description of the problem currentTotalExecutionsCount
shouldn'
t affect the probability of the exception. Therefore one can just do the following:
import java.util.Random;
...
Boolean shouldThrow(int probabilityPercentage) {
Random generator = new Random(System.currentTimeMillis());
return generator.nextDouble() * 100 < probabilityPercentage ? true: false;
}
If you wanted the probability to change based on currentTotalExecutionsCount
then you would need to adopt the random generator accordingly.