Firstly, would appreciate some code-review feedback, from a TDD and design perspective.
Secondly, what are your thoughts on implementing test case: testNumbersAreUnique()
? The fact that API returns a Set
of immutable objects means elements will be unique, but just wanted to know your thoughts. The reason I used a do-while
as against a while
or for
loop (and iterate ‘x’ times to populate ‘x’ Random numbers) is to ensure the set has correct number of elements (which will of course be unique) even if the random number gives something that is already existing in the Set.
The problem: Lottery Generator
The goal of the program is to generate ‘x’ distinct lottery numbers within a given range 1 to ‘N’. Both x and N are int for simplicity.
Following is my code. I wrote a controller, which will call service layer to fetch ‘x’ distinct lottery numbers:
public class Controller {
private LotteryGeneratorService lotteryGeneratorService;
@RequestMapping(method=RequestMethod.GET)
public Set<Integer> getLotteryNumbers(int x){
lotteryGeneratorService = new LotteryGeneratorService();
return lotteryGeneratorService.generateNRandom (x);
}
}
This is the Service class:
public class LotteryGeneratorService {
private Set<Integer> set = new HashSet<>();
private static int generateRandomInt(){
Random random = new Random();
return random.nextInt(N);
}
public Set<Integer> generateNRandom(int x){
int tmp;
do{
tmp =generateRandomInt();
if(tmp!=0)
set.add(tmp);
}
while(set.size()<x);
return set;
}
public int getSizeOfRandomlyGeneratedSet(){
return set.size();
}
}
The tests:
public class LotteryTest {
LotteryGeneratorService lotteryGeneratorService;
int N;
@Before
public void setup() {
lotteryGeneratorService = new LotteryGeneratorService();
N=100;
}
@After
public void tearDown() {
lotteryGeneratorService = null;
}
@Test
public void testNumberOfNumbersGeneratedIsCorrect() {
assertEquals(6, lotteryGeneratorService.generateNRandom(6).size());
}
@Test
public void testRangeIsCorrect() {
Set<Integer> set = lotteryGeneratorService.generateNRandom(6);
for (int i : set) {
assertTrue(i >= 1 && i <= N);
}
}
@Test
public void testNumbersAreUnique() {
//..?
}
}
N
defined inreturn random.nextInt(N);
insideLotteryGeneratorService
? \$\endgroup\$