Reputation: 23
I am currently trying to write some Unit Tests for a project of mine that stores lists of details about sessions in a gym and have no idea how to do so as Unit Testing is rather new to me. The method to serialize is SaveState() and the method to deserialize is LoadState() and both work perfectly fine when ran thankfully, I just need to write some unit tests to prove that at quickly. The list(session) that allSessions takes from is from another class that holds the data but I don't know if that is actually needed when testing or if you just substitute something else in within the test itself. Any help is greatly appriciated.
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();
}
}
Upvotes: 1
Views: 1172
Reputation: 4007
unit testing actually shows parts of the code that can be designed in more smart way
I'd like you to suggest to refactor the SessionsManager
class and add new methods that will do serialization into stream (input parameter) like
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);
}
then you can
SessionsManager
classpublic 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.
}
}
Upvotes: 2