2

I'm trying to get a handle on TDD. I'm creating a class which reads characters from a file, building words character by character.

The part I'm having a little trouble with is the method which builds the word and returns it.

public string GetNextWord()
{
    // please ignore implementation of characterReader,
    // I'm just using it as an example, I believe implementation is
    // irrelevant when unit testing, correct me if wrong
    return characterReader.NextWord();
}

How would I do this in a TDD manner? I've currently got a test file with known content. I pass that in to be read and check the words being returned match what's in the input file in the correct order.

Text file content: Test file content one End.

Unit test

string word1 = wordBuilder.GetNextWord();
string word2 = wordBuilder.GetNextWord();
.
.
Assert.IsTrue(String.Equals(word1, "Test");
.
.

Is this correct? I don't feel 'right' about having the test depend on an external input file and checking against hard coded strings. Could someone expound the correct TDD way of doing this please? :)

redspidermkv
  • 503
  • 10
  • 25
  • "I believe implementation is irrelevant when unit testing, correct me if wrong". You are wrong. Implementation is **always** relevant. Remember, TDD goes failing -> passing -> **refactor**. – Daniel Mann Aug 02 '15 at 20:53
  • But from the point of view of the unit test, implementation shouldn't matter as it doesn't affect the test (the test affects implementation, please correct if wrong :) ) – redspidermkv Aug 02 '15 at 20:54
  • 1
    That is correct -- during the transition from "failing" to "passing", your concern is having all the tests pass. Afterwards, you worry about the implementation. This question is too general to answer (it would probably be a better fit for programmers Stack Exchange), but basically, start with a the simple cases and work up to more complex ones. What happens when your input file doesn't exist? What happens if the file is empty? What happens if the file contains one letter? The first test might be "I can instantiate this class and get a valid instance". – Daniel Mann Aug 02 '15 at 20:58
  • I forgot to mention, I do already have tests in place for when the file doesn't exist or is empty. I didn't think the previous tests would matter as the tests are supposed to be independent. Is it ok to have a test where you check against known values in the file? It just feels like the test is tightly coupled on something external.. – redspidermkv Aug 02 '15 at 21:03

1 Answers1

1

Yes, in general it is better to let each unit test be unreliant of external factors.

For your test you can consider creating a temp file during test setup, which your test assert is read correctly. By doing this you also have access to the file's string contents in the code.

Community
  • 1
  • 1
ghdalum
  • 891
  • 5
  • 17