开发者

Unit testing a method that writes serialized objects to a file

I have a static method that writes serialized object. How can I write JUnit tests to see if it works? Here is my method...

    public sta开发者_StackOverflow中文版tic void writeToDisk(Data data){

     try{
            FileInputStream fis = new FileInputStream(filename);                             ObjectInputStream in = new ObjectInputStream(fis);
            dataList = (DataList) in.readObject();
            in.close();         
        }
        catch(Exception e){
            dataList = new DataList();
            System.out.println("New file created!");
        }

        dataList.insertData(data);

        try{
            FileOutputStream fos = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(dataList);
            out.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }

        }   
    }


Start with no file.

Call the method with test Data argument. Then read it back from resulting file (pull data from list as needed) and compare to original.

Repeat with new objects to see if new data is added successfully.


Change your function to accept an InputStream. In production, pass a FileInputStream, in tests, pass a different InputStream which you can then check to make sure it contains the correct value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜