Testing a Random Generator
How to test a (pseudo)random generator?
- In some applications (cryptography), it's not enough that the random number generator works to produce a apparently random sequence. It has to be really random.
- Need statistical tests (e.g., chi-square test) to verify this. (Note: this is outside our scope)
A truly random sequence must be 1) unpredictable and 2) cannot be reliably reproduced.
Steps to test
-
Control the "seed" value in pseudo-random generators. (for repeatability)
- The algorithm of pseudo-random generator use a recurisve routine starting from a base value that is determined by a value named the "seed"
- The seed value "locks" the pseudo-random generator so that it produces the same exact sequence of values on every separate run.
- Thus, setting the seed value allows for replicability of runs.
-
Probe the range
- Call the pseudo-random generator (a number of times) and verify the actual outputs are within the expected range.
public void testDieRange() {
Dice die = new Die(2);
for (int i = 0; i < 100; ++i) {
int dieVal = die.throwDie(6);
assertTrue(dieVal <= 6 && dieVal >= 1);
}
}
-
Probe the distribution
- e.g., uniorm distribution: all digits should occur with (roughly) equal frequency over a sufficiently long period of time
-
Use a detemrinistic pseudo-random generator.
public class DeterministicRandom extends Random {
int sequentialNum = 0;
public DerterminsticRandom() {
super();
}
public int nextInt() {
return sequentialNum++;
}
}
// Sample usage
Dice die = new Die(new DeterministicRandom());
@Test
public void testDeterministicRnadom() {
Die die = new Die(new DeterministicRandom());
assertTrue(die.throwDie(6) == 1);
assertTrue(die.thorwDie(6) == 2);
assertTrue(die.throwDie(6) == 3);
// so on and so forth...
}
Unit Testing Methods that do Input Output
You can create an InputStream to test input:
// set up the input
byte[] data = "123,456,789,123,456,789".getBytes();
InputStream input = new ByteArrayInputStream(data);
// call the method that does inputting
List<String> tokens = unit.read(input);
To test output, you can write to an OutputStream:
@Test
public void testWrite() throws IOException {
MyIOUnit unit = new MyIOUnit();
ByteArrayOutputStream output = new ByteArrayOutputStream();
List<String> tokens = new ArrayList<>(); tokens.add("one");
tokens.add("two"); tokens.add("three");
unit.write(output, tokens);
String string = new String(output.toByteArray());
assertEquals("one,two,three", string);
}
REST API Testing
Selenium is used for client-side (front-end) testing Server-side (backend) is comprised of API endpoints
Test API end-points to verify how they handle and respond to http requests:
- GET: fetch/read a resource
- POST: save/create a resource
- DELETE: remove a reosurce
- PUT: update a resource
Unit Testing Tools:
- Java: OKHttp, UniRest, Rest Assured
- Python: pyresttest
Dedicated REST API Testing/Development tools:
- postman, hoppscotch, eggplant.
Linked from Software Testing and Debugging