I'm trying to test the behaviour of a method to generate a URL with a few parameters. The method makes use of a helper method which in turn makes use of new Random().nextDouble()
.
private static String generateChecksum() {
return "s" + new Double(Math.floor(Instant.now().getEpochSecond() / 10800000)).longValue() % 10 +
new Double(Math.floor(10000000000000L * new Random().nextDouble())).longValue();
}
My goal for this particular test is to ensure the output of the method matches what I expect. My issue is I can't predict the result of Random.nextDouble()
.
I read you can mock the results and I thought that overriding every instance of that method. I found out I couldn't do that but also that I shouldn't, but instead I should re-write my code to fit my test.
How do I rewrite it? Do I pass the checksum into the method pre-generated along with the parameters so my flow goes from:
1. Main()
2. generateUrl(params)
2a. generateChecksum() // for use in generateUrl
3. return URL
to
1. Main()
2. generateChecksum()
3. generateUrl(params, checksum)
4. return URL
Or am I missing something? Thanks!