WeightedAverageFitnessCalculator implements VMTaskFitnessCalculator { @Override public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) { double totalWeightedScores = 0.0; double totalWeights = 0.0; for (WeightedFitnessCalculator calculator : calculators) { double score = calculator.getFitnessCalculator().calculateFitness(taskRequest, targetVM, taskTrackerState); if (score == 0.0) { return score; } totalWeightedScores += (score * calculator.getWeight()); totalWeights += calculator.getWeight(); } return totalWeightedScores / totalWeights; } WeightedAverageFitnessCalculator(List<WeightedFitnessCalculator> calculators); @Override String getName(); @Override double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState); @Override String toString();  }
@Test public void testCalculatorWeightedAverage() throws Exception { VMTaskFitnessCalculator fitnessCalculator1 = mock(VMTaskFitnessCalculator.class); when(fitnessCalculator1.calculateFitness(any(), any(), any())).thenReturn(0.5); VMTaskFitnessCalculator fitnessCalculator2 = mock(VMTaskFitnessCalculator.class); when(fitnessCalculator2.calculateFitness(any(), any(), any())).thenReturn(1.0); List<WeightedFitnessCalculator> weightedFitnessCalculators = Arrays.asList( new WeightedFitnessCalculator(fitnessCalculator1, 0.5), new WeightedFitnessCalculator(fitnessCalculator2, 0.5) ); WeightedAverageFitnessCalculator calculator = new WeightedAverageFitnessCalculator(weightedFitnessCalculators); double fitness = calculator.calculateFitness(mock(TaskRequest.class), mock(VirtualMachineCurrentState.class), mock(TaskTrackerState.class)); Assert.assertEquals(0.75, fitness, 0.0); }
@Test public void testCalculatorWeightedAverageWithZero() throws Exception { VMTaskFitnessCalculator fitnessCalculator1 = mock(VMTaskFitnessCalculator.class); when(fitnessCalculator1.calculateFitness(any(), any(), any())).thenReturn(0.0); VMTaskFitnessCalculator fitnessCalculator2 = mock(VMTaskFitnessCalculator.class); when(fitnessCalculator2.calculateFitness(any(), any(), any())).thenReturn(1.0); List<WeightedFitnessCalculator> weightedFitnessCalculators = Arrays.asList( new WeightedFitnessCalculator(fitnessCalculator1, 0.3), new WeightedFitnessCalculator(fitnessCalculator2, 0.7) ); WeightedAverageFitnessCalculator calculator = new WeightedAverageFitnessCalculator(weightedFitnessCalculators); double fitness = calculator.calculateFitness(mock(TaskRequest.class), mock(VirtualMachineCurrentState.class), mock(TaskTrackerState.class)); Assert.assertEquals(0.0, fitness, 0.0); }