STFitnessEvaluator implements FitnessEvaluator<T> { @Override public double getFitness(T candidate, List<? extends T> population) { if (this.population == null || this.population != population) { evaluations.clear(); evaluate(population, evaluations); this.population = population; } int index = population.indexOf(candidate); Preconditions.checkArgument(index != -1, "Candidate is not part of the population"); return evaluations.get(index); }  @Override double getFitness(T candidate, List<? extends T> population);  }
@Test public void testEvaluateSamePopulation() { STFitnessEvaluatorMock<Integer> mock = new STFitnessEvaluatorMock<Integer>(); RandomUtils.useTestSeed(); Random rng = RandomUtils.getRandom(); int size = 100; List<Integer> population = randomInts(size, rng); List<Double> evaluations = randomFloats(size, rng); mock.shouldReturn(evaluations); for (int index = 0; index < size; index++) { Integer candidate = population.get(index); assertEquals(evaluations.get(index), mock.getFitness(candidate, population), EPSILON); } assertEquals(1, mock.getNbCalls()); }
@Test public void testEvaluateDifferentPopulations() { STFitnessEvaluatorMock<Integer> mock = new STFitnessEvaluatorMock<Integer>(); RandomUtils.useTestSeed(); Random rng = RandomUtils.getRandom(); int size = 100; List<Integer> population = randomInts(size, rng); List<Double> evaluations = randomFloats(size, rng); mock.shouldReturn(evaluations); mock.getFitness(population.get(rng.nextInt(size)), population); population = randomInts(size, rng); mock.getFitness(population.get(rng.nextInt(size)), population); assertEquals(2, mock.getNbCalls()); }