gpt4 book ai didi

java - 如何通过 JUNIT 将数据与文件进行比较?

转载 作者:行者123 更新时间:2023-12-01 19:11:38 24 4
gpt4 key购买 nike

应该执行的测试:

@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> 。请注意,我重命名了您的方法以遵循标准驼峰命名约定。

@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());
}
}

关于java - 如何通过 JUNIT 将数据与文件进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59477741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com