Can an expert TDD person show me where I went wrong?
Please be as brutally honest as possible. I am keen to learn from whatever mistake(s) I have made.
I just failed a job interview which wanted people skilled in TDD . I was given the following task.
Write code that will;
1) Read an input file.
2) Reverse the contents.
3) Write the reversed contents to an output file.
Example:
Input file contains “Company”
After processing the input file, an output file should be written containing "ynapmoC"
Here is one of the main test that I created using TDD.
I think the main thing to point out is that I isolated the actual file read/write functionality by wrapping it in my own interface. So the test does not actually read or write files. (I had other tests checking for empty strings, nulls, and non existent files.)
[TestMethod]
public void ThreeCharactersShouldBeReversed()
{
Mockery mockery = new Mockery();
IReadWriter readWriter = (IReadWriter)mockery.NewMock(typeof(IReadWriter));
Expect.Once.On(readWriter).Method("ReadStreamContent").Will(Return.Value("XYZ"));
Expect.Once.On(readWriter).Method("WriteStreamContent").With("ZYX");
IReverser reverser = new ContentReverser(readWriter);
bool result = reverser.ReverseFileContents();
Assert.IsTrue(result, "Expected true to be returned indicating success");
mockery.VerifyAllExpectationsHaveBeenMet();
}
Here’s the reverser class.
public interface IReverser
{
bool ReverseFileContents();
}
public class ContentReverser : IReverser
{
private readonly IReadWriter _readWriter;
public ContentReverser(IReadWriter readWriter)
{
_readWriter = readWriter;
}
public bool ReverseFileContents()
{
bool result;
try
{
string sourceContent = _readWriter.ReadStreamContent();
char[] originalContent = sourceContent.ToCharArray();
Array.Reverse(originalContent);
string reversedContent = new string(originalContent);
_readWriter.WriteStreamContent(reversedContent);
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
}
Here’s a class that actually does read/writing of files. (Not used by the above Test, Although during the interview I wrote a UI that instantiated and passed in one of these classes to demonstrate integration testing)
public interface IReadWriter
{
string ReadStreamContent();
void WriteStreamContent(string fileContent);
}
/// <summary>
/// This is the physical file read and write mechanism.
/// </summary>
public class ReadWriter : IReadWriter
{
private readonly string _sourceFile;
private readonly string _targetFile;
public ReadWriter(string sourceFile, string targetFile)
{
_sourceFile = sourceFile;
_targetFile = targetFile;
}
public string ReadStreamContent()
{
return System.IO.File.ReadAllText(_sourceFile);
}
public void WriteStreamContent(string fileContent)
{
System.IO.File.WriteAllText(_targetFile, fileContent);
}
}