How to do unit testing of a file recording method using Visual Studio built-in automated tests?

  • I am using Visual Studio 2008 Professional automated tests. I have a function that writes to a file. I want the unit test file write function. I read somewhere that I would somehow have to scoff at the file. I do not know how to do that. You can help?

  • How to unit test a method that loads a page from the Internet?

+5
source share
4 answers

It depends on how close your code is to nuts'n'bolts; for example, you could work instead Streamand pass the code MemoryStreamto code (and check the contents). You can simply write to the file system (in the tempo area), check the contents and then pop it out. If your code is slightly above the file system, you can write a mockable IFileSysteminterface using the high-level methods you need (e.g. WriteAllBytes/ WriteAllText). It would be painful to mock the streaming APIs.

( )... () IWebClient (, DownloadString ..); , - WebClient . , .

+6

, . , , MemoryStream. , FileStream .

, ( , ), , , Stream.

+7

, , , unit test.

, , , .

-.

interface IFileService
{
     Stream CreateFile(string filename); 
}

class InMemoryFileService : IFileService
{
    private Dictionary<string, MemoryStream> files = new Dictionary<string, MemoryStream>();

    public Stream CreateFile(string filename)
    {
       MemoryStream stream = new MemoryStream();
       files.Add(filename, stream);
       return stream;
    }

    public MemoryStream GetFile(string filename)
    {
         return files[filename];
    }
} 

GetFile, , .

+4

Actually, you do not want the call to write the file directly to your function, but instead transfer the input / output of the files inside the class using the interface.

Then you can use something like Rhino Mocks to create a mock class that implements the interface.

+1
source

All Articles