Mike Cole
Mike Cole

Reputation: 14713

How can I unit test this C# extension method?

I'm just not sure how to mock up a situation to test this. Should I actually create a file on the file system?

public static void DeleteIfExists(this FileInfo fileInfo)
{
   if (fileInfo.Exists)
   {
      fileInfo.Delete();
   }
}

Upvotes: 3

Views: 6161

Answers (1)

tvanfosson
tvanfosson

Reputation: 532455

I'd use a mocking 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 for when Delete throws an exception, etc.

Upvotes: 8

Related Questions