Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test a file writing method with Visual Studio's built-in automated tests?

  1. I use Visual Studio 2008 Professional automated tests. I have a function that writes to a file. I want to unit test the file writing function. I have read somewhere that I would have to mock a file somehow. I don't know how to do it. Can you help?

  2. How to unit-test a method that downloads a page from the Internet?

like image 259
Jader Dias Avatar asked Jan 16 '09 12:01

Jader Dias


2 Answers

If the method has to open the file stream itself, then that's hard to mock. However, if you can pass a stream into the method, and make it write to that, then you can pass in a MemoryStream instead. An alternative overload can take fewer parameters, open the file and pass a FileStream to the other method.

This way you don't get complete coverage (unless you write a test or two which really does hit the disk) but most of your logic is in fully tested code, within the method taking a Stream parameter.

like image 90
Jon Skeet Avatar answered Oct 01 '22 00:10

Jon Skeet


It depends how close your code is to the nuts'n'bolts; for example, you could work in Streams instead, and pass a MemoryStream to the code (and check the contents). You could just write to the file-system (in the temp area), check the contents and ditch it afterwards. Of if your code is a bit above the file system, you could write a mockable IFileSystem interface with the high-level methods you need (like WriteAllBytes / WriteAllText). It would be a pain to mock the streaming APIs, though.

For downloading from the internet (or pretending to)... you could (for example) write an IWebClient interface with the functions you need (like DownloadString, etc); mock it to return fixed content, and use something like WebClient as the basis for an actual implementation. Of course, you'll need to test the actual implementation against real sites.

like image 29
Marc Gravell Avatar answered Oct 01 '22 01:10

Marc Gravell