Basically I have some methods that access the file system and to avoid that in the unit test I have broken those sections out into a protected virtual method. In the Unit Test I then use Moq to setup those protected methods the way I want. I am just curious if I am going about this correctly or is there a better way? Below is an example method I have done this with however I have several places I do this with.
Method that gets unit tested:
public IEnumerable<ConfigProfile> GetSavedProfiles(string product)
{
if(string.IsNullOrEmpty(product))
{
throw new ArgumentNullException("product");
}
string profileDirectory = _factory.GetCustomProfileDirectory(product);
List<ConfigProfile> profiles = Enumerable.Empty<ConfigProfile>().ToList();
_logger.Debug("Getting Saved profiles.");
IList<FileInfo> files = GetProfilesInDirectory(profileDirectory).ToList();
if (!files.Any())
{
_logger.Debug(string.Format("No custom profiles found for {0}.", product));
return profiles;
}
profiles.AddRange(files.Select(LoadProfile));
return profiles;
}
Then I have these two protected methods I have taken out and setup in my unit test:
protected virtual IEnumerable<FileInfo> GetProfilesInDirectory(string directory)
{
DirectoryInfo files = new DirectoryInfo(directory);
return files.EnumerateFiles("*.ecu");
}
protected virtual ConfigProfile LoadProfile(FileInfo file)
{
ConfigProfile profile;
using (FileStream stream = new FileStream(file.FullName, FileMode.Open))
{
profile = _serializer.DeserializeFromDisk(stream);
}
return profile;
}
BinaryFormatter
in favour of a well defined format based on the public properties of an object. It might be a good idea to use special DTO classes for serialization instead of the model itself. – CodesInChaos Jan 26 at 17:12