Share via


2008 Advent Calendar December 20th

 

   1:      public class Advent20
   2:      {
   3:          private FileUtilWithDelete Given_A_File(string content, bool readable)
   4:          {
   5:              FileUtilWithDelete file = new FileUtilWithDelete("SomeFile.txt");
   6:              file.Create(content);
   7:              file.Readable = readable;
   8:              return file;
   9:          }
  10:   
  11:          [Fact]
  12:          public void Reading_A_Readable_File_Returns_File_Content()
  13:          {
  14:              using (FileUtilWithDelete file = Given_A_File("CONTENT", true))
  15:              {
  16:                  string content = file.Read();
  17:                  Assert.Equal<string>("CONTENT", content);
  18:              }
  19:          }
  20:   
  21:          [Fact]
  22:          public void Reading_An_Unreadable_File_Throws_Correct_Exception()
  23:          {
  24:              using (FileUtilWithDelete file = Given_A_File("SHOULD NOT BE ABLE TO READ THIS", false))
  25:              {
  26:                  Assert.Throws<AccessViolationException>(() => { file.Read(); });
  27:              }
  28:          }
  29:      }

The "Given_By" pattern has been "stolen" from BDD and the whole purpose is to make the test as readable as possible. Reading a test should more or less be like reading a paragraph. So "Given_A_File" is not really that great. It is probably better to have different Given-methods depending on what we want.