0

I am trying to use Moq and Nunit to test a method of this form: crc

public long computeCRC(string filepath)
{
   long crc;

    ...open file at filepath compute crc...

   return crc;
}

I don't want the file at filepath to be on a drive (I might not have read/write access). I would like to fill a stream with the same content every time in the test code (because I know the correct CRC for that content), get a filepath for the stream and be able to hand that filepath to the method being tested.

davecove
  • 1,001
  • 4
  • 16
  • 36
  • Then don't use file classes or something like that directly but something abstract that can be exchanged. As you are talking about Moq i could phrase it as "create something that can be mocked away". – Ralf Nov 10 '21 at 18:39
  • I get that... but what would that 'something' be? – davecove Nov 10 '21 at 19:24
  • 1
    For example an IFileSystem interface with an FileSystem implementation class that encapsulates all FileSystem stuff you need. And for testing you don't inject the concrete Filesystem class but a moq returning the data from somwhere instead of the real Filesystem. – Ralf Nov 10 '21 at 19:39
  • 1
    https://stackoverflow.com/questions/266776/mock-file-methods-in-net-like-file-copy1-txt-2-txt?noredirect=1&lq=1 has an example for an IFile interface so things like File.Copy etc. can be mocked away. Not quite the same as what you want but close enough so you should get the idea. – Ralf Nov 10 '21 at 19:51
  • If you use only the contents of the file in the method, I would change the signature to `public long computeCRC(IStream input)`. Then you are free to pass e.g. a MemoryStream in the test. – Klaus Gütter Nov 11 '21 at 04:46

0 Answers0