[英]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();
}
}
I'd use a mocking framework, like RhinoMocks . 我会使用像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. Delete时抛出异常等的其他测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.