How can I unit test use this C # extension method?

I'm just not sure how the layout of the situation is to test this. Should I create a file in the file system?

public static void DeleteIfExists(this FileInfo fileInfo)
{
   if (fileInfo.Exists)
   {
      fileInfo.Delete();
   }
}
+3
source share
1 answer

I would use a fake framework like RhinoMocks .

[Test]
public void ShouldDeleteAFileWhenItExists()
{
    var mockInfo = MockRepository.GenerateMock<FileInfo>();
    mockInfo.Expect( i => i.Exists ).Return( true ).Repeat.Once();
    mockInfo.Expect( i => i.Delete() ).Repeat.Once();

    var extensions = new FileInfoExtensions();

    extensions.DeleteIfExists( mockInfo );

    mockInfo.VerifyAllExpectations();
}

[Test]
public void ShouldNotDeleteAFileWhenItDoesNotExist()
{
    var mockInfo = MockRepository.GenerateMock<FileInfo>();
    mockInfo.Expect( i => i.Exists ).Return( false ).Repeat.Once();
    mockInfo.Expect( i => i.Delete() ).Repeat.Never();

    var extensions = new FileInfoExtensions();

    extensions.DeleteIfExists( mockInfo );

    mockInfo.VerifyAllExpectations();
}

Other tests when Delete throws an exception, etc.

+8
source

All Articles