gpt4 book ai didi

java - 如何编写涉及javafx文件选择器的序列化和反序列化测试?

转载 作者:行者123 更新时间:2023-12-02 02:10:28 26 4
gpt4 key购买 nike

我需要为serialization()和deserialization()函数编写单元测试,但我不知道如何覆盖FileChooser和FileInputStream。

还有,如果这个文件中有两个函数,我必须写两个且仅两个相应的测试函数?

两个函数如下:

/**
* serialize and save all the datasets and charts
* @param myDataset
* pass all the existing datasets into this function for serialization purpose
* @param myChart
* pass all the existing charts into this function for serialization purpose
*/

public static void serialize (HashMap<String, DataTable> myDataset, HashMap<String, Chart> myChart) {

// first, let the user select a directory to save
FileChooser chooser = new FileChooser();
chooser.setTitle("Save");
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("comp3111 type", "*.comp3111");
chooser.getExtensionFilters().add(extFilter);
File file = chooser.showSaveDialog(new Stage());

try {
FileOutputStream fOutput = new FileOutputStream(file);
ObjectOutputStream objOutput = new ObjectOutputStream(fOutput);

// put all the DataTable type objects into an array
objOutput.writeObject(myDataset);
objOutput.writeObject(myChart);

objOutput.close();
fOutput.close();

} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}


/**
* choose a file with *.comp3111 extension for deserialization purpose
* @return
* the chosen *.comp3111 file
*/
public static File deserialize () {
FileChooser chooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("comp3111 type", "*.comp3111");
chooser.getExtensionFilters().add(extFilter);

File mfile = chooser.showOpenDialog(new Stage());
return mfile;
}

最佳答案

问题是您的 serializedeserialize 方法中存在不属于其中的代码。它们太广泛了:它们不仅序列化和反序列化对象(尽管反序列化的代码似乎丢失),而且还打开文件选择器。

虽然从程序流程的角度来看这可能有意义,但它也打破了 single responsibility principle (注意:我知道 SRP 通常应用于类而不是方法)。你的方法做了太多事情。

因此,您应该以这样的方式编写方法,使其接受 FileInputStream 作为输入参数,并返回对象集合作为结果(例如反序列化),或者获取对象集合并返回一个 OutputStream 作为结果(用于序列化)。这样,您就可以准确地测试该行为。

更好的是首先编写测试,例如,您可以使用测试文件,既可以从中读取以检查它是否生成预期的对象,也可以测试 ByteOutputStream 返回序列化器匹配同一个文件。

它的名字是test-driven development ,这是编写可测试且稳定的代码的好方法。

关于java - 如何编写涉及javafx文件选择器的序列化和反序列化测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50119202/

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