[英]How to Perform Unit testing for Serialization and Deserialization of a class in C#?
[英]How would I Unit Test these Serialization/Deserialization methods in C#?
我目前正在嘗試為我的一個項目編寫一些單元測試,該項目存儲有關健身房會話的詳細信息列表,並且不知道如何這樣做,因為單元測試對我來說相當新。 序列化的方法是 SaveState() 和反序列化的方法是 LoadState() 並且在運行時都可以正常工作,我只需要編寫一些單元測試來快速證明這一點。 allSessions 從中獲取的列表(會話)來自另一個保存數據的 class 但我不知道在測試時是否真的需要它,或者您是否只是在測試本身中替換其他東西。 非常感謝任何幫助。
public class SessionsManager
{
const string FILENAME = "SessionFile.dat";
//declare private list for events
private List<Session> allSessions;
// Public Property
public List<Session> AllSessions { get => allSessions; set => allSessions = value; }
//creating constructor to hold lists
public SessionsManager()
{
AllSessions = new List<Session>();
}
public void SaveState()
{
//Formatter object
BinaryFormatter biFormatter = new BinaryFormatter();
//stream object to create file types
FileStream outFile = new FileStream(FILENAME, FileMode.Create, FileAccess.Write);
//Save the whole list in one
biFormatter.Serialize(outFile, allSessions);
//Close the stream, dont want them crossing after all
outFile.Close();
}
public void LoadState()
{
//Formatter object
BinaryFormatter biiFormatter = new BinaryFormatter();
//stream object to read file
FileStream InFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
//Deserialise the whole list
allSessions = ((List<Session>)biiFormatter.Deserialize(InFile));
//close stream
InFile.Close();
}
}
單元測試實際上展示了可以以更智能的方式設計的部分代碼
我希望您建議重構SessionsManager
class 並添加將序列化到 stream (輸入參數)的新方法,例如
public static T LoadState<T>(Stream stream)
{
BinaryFormatter biiFormatter = new BinaryFormatter();
return (T)biiFormatter.Deserialize(stream);
}
public static void SaveState<T>(Stream stream, T value)
{
BinaryFormatter biFormatter = new BinaryFormatter();
biFormatter.Serialize(outFile, value);
}
那么你也能
SessionsManager
class 中使用這些方法public void TestSerialize()
{
using (var ms = new MemoryStream())
{
SessionsManager.SaveState(ms, new List<Session>() { new Session() } );
ms.Position = 0;
var res = SessionManager.LoadState<List<Session>>(ms);
Assert.AreEqual(1, res.Count); // check that there are the same count of elements e.g.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.