Mock File IO static class in c#

2019-06-18 05:14发布

I am new to Unit Testing, and I need to mock the File static class in System.IO namespace. I am using Rhinomock, what is the best way to accomplish this,

Lets say I need to mock the File.Exists,File.Delete ...

7条回答
贼婆χ
2楼-- · 2019-06-18 05:53

Why not using MS Fakes? Wouldn't that be simple, already supported compared to RhinoMocks, SystemWrapper.Wrapper and SystemWrapper.Interface?

查看更多
成全新的幸福
3楼-- · 2019-06-18 05:58

You can't mock static methods with Rhino mock. See this question for more info. You could create a facade class to wrap the file system calls you will use and then create a mock version of that.

查看更多
在下西门庆
4楼-- · 2019-06-18 06:03

You can use moq framework for this.It is open source google project which you can download from here. Download Moq framework

To get fully understanding about how to use moq with C# please refer the following article.

http://learningcsharpe.blogspot.com/2011/11/how-to-use-moq-library-for-your-unit.html

thanks, Erandika.

查看更多
乱世女痞
5楼-- · 2019-06-18 06:04

See also Vadim's SystemWrapper. You can mock a lot of system classes with it, but you will need to apply the dependency injection pattern to make your code testable.

[Test]
public void Check_that_FileInfo_methods_Create_and_Delete_are_called()
{
    // Add mock repository.
    IFileInfoWrap fileInfoRepository = MockRepository.GenerateMock<IFileInfoWrap>();
    IFileStreamWrap fileStreamRepository = MockRepository.GenerateMock<IFileStreamWrap>();

    // Create expectations
    fileInfoRepository.Expect(x => x.Create()).Return(fileStreamRepository);
    fileStreamRepository.Expect(x => x.Close());
    fileInfoRepository.Expect(x => x.Delete());

    // Test
    new FileInfoSample().CreateAndDeleteFile(fileInfoRepository);

    // Verify expectations.
    fileInfoRepository.VerifyAllExpectations();
    fileStreamRepository.VerifyAllExpectations();
}  
查看更多
一纸荒年 Trace。
6楼-- · 2019-06-18 06:12

I also used wrapper classes. I use this tool to easily generate wrapper classes such as System.IO.File

https://www.nuget.org/packages/Digitrish.WrapperGenerator/

Once you installed the package just type the following on Package Manager Console

Scaffold Wrapper System.IO.File

This will generate IFile.cs interface and one concreate wrapper class File.cs. Then you can use the IFile to Mock and File.cs for the real implementation.

查看更多
Lonely孤独者°
7楼-- · 2019-06-18 06:13

In addition to the you can't mock Static easily answer.

I'd like to point out that you shouldn't be mocking File.IO type, because it is not a type that you own. You should only Mock types that you own.

查看更多
登录 后发表回答