应执行的测试:
@Test
public void Should_Create_List_Of_Racers_And_Put_It_To_Map() throws IOException {
RacerListPrinter racerListPrinter = new RacerListPrinter();
Should_Create_List_Of_Racers();
assertEquals(racerListPrinter.printRacerList(Should_Create_List_Of_Racers()), );
}
其中
Should_Create_List_Of_Racers();
:@Test
public List<Racer> Should_Create_List_Of_Racers() throws IOException {
List<Racer> listOfRacers = new ArrayList<>();
SortedListOfRacers racerList = new SortedListOfRacers();
Racer racer1 = new Racer("SVF", "Sebastian Vettel", "FERRARI");
racer1.setResult("1:04.415");
listOfRacers.add(racer1);
Racer racer2 = new Racer("DRR", "Daniel Ricciardo", "RED BULL RACING TAG HEUER");
racer2.setResult("1:12.013");
listOfRacers.add(racer2);
Racer racer3 = new Racer("VBM", "Valtteri Bottas", "MERCEDES");
racer3.setResult("1:12.434");
listOfRacers.add(racer3);
我的文件位于资源中,名为
finalResultForTesting.txt
,我需要比较方法
Should_Create_List_Of_Racers()
和这一行中的文件:
assertEquals(racerListPrinter.printRacerList(Should_Create_List_Of_Racers()));
racerListPrinter.printRacerList(List<Racer>)
的输出格式:1. Sebastian Vettel | FERRARI | 1:04.415
2. Daniel Ricciardo | RED BULL RACING TAG HEUER | 1:12.013
3. Valtteri Bottas | MERCEDES | 1:12.434
最佳答案
这是java8上的有效解决方案。我期望RacerListPrinter
返回List<String>
。
请注意,我重命名了您的方法,以遵循标准的camelCase约定。
@Test
public void shouldPrintRacerListInCorrectFormat() throws Exception {
RacerListPrinter racerListPrinter = new RacerListPrinter();
// yours Should_Create_List_Of_Racers()
List<Racer> actualRacers = populateRacerList();
List<String> actualRacersOutput = racerListPrinter.printRacerList(actualRacers);
List<String> expectedRacersOutput = loadRacerListFromFile("finalResultForTesting.txt");
assertEquals(expectedRacersOutput, actualRacersOutput);
}
private List<String> loadRacerListFromFile(String fileName) throws URISyntaxException, IOException {
Path path = Paths.get(getClass().getClassLoader()
.getResource(fileName).toURI());
// use try-with-resources in order to ensure stream is closed
try (Stream<String> lines = Files.lines(path)) {
return lines.collect(Collectors.toList());
}
}