TDD FileLoader v1.2
In this solution, the production class actually loads a file from the disk via the test
The Unit Test
using NUnit.Framework;
using file_loader_service;
using System.Collections.Generic;
using System.IO;
namespace file_loader_tests
{
public class FileLoaderTests
{
[Test]
public void load_all_of_file_using_inbuilt_Files_type()
{
// arrange
string fileToLoad = "c:/tmp/KeyboardHandler.java.txt";
FileLoader cut = new FileLoader();
int expectedBytesRead = 1383;
// act
int bytesRead = cut.LoadFile(fileToLoad);
// assert
Assert.AreEqual(expectedBytesRead, bytesRead);
}
[Test]
public void load_all_of_file_using_inbuilt_Files_type_via_lambda()
{
// arrange
string fileToLoad = "c:/tmp/KeyboardHandler.java.txt";
FileLoader cut = new FileLoader();
int expectedBytesRead = 1383;
// act
int bytesRead = cut.LoadFile(fileToLoad, (fname) =>
{
IEnumerable<string> result = null;
try
{
result = File.ReadLines(fname);
}
catch (IOException e) { }
return result;
});
// assert
Assert.AreEqual(expectedBytesRead, bytesRead);
}
}
}
The CUT FileLoader
using System;
using System.Collections.Generic;
using System.IO;
namespace file_loader_service
{
public delegate IEnumerable<string> ILoadFile(String fname);
public class FileLoader
{
IEnumerable<string> lines = new List<string>();
public FileLoader()
{
}
public int LoadFile(string fname, ILoadFile func)
{
lines = func(fname);
return CalculateFileSize();
}
public int LoadFile(string fname)
{
try
{
lines = File.ReadLines(fname);
}
catch (IOException e) { }
return CalculateFileSize();
}
private int CalculateFileSize()
{
int result = 0;
foreach (string line in lines)
{
result += line.Length;
};
return result;
}
}
}