0

I want to write a unit-test for the following codesnippet:

var attachment = new Attachment(path)
{
   ContentId = Path.GetFileName(path)
};

return attachment;

Unfortunately the Attachment ctor throws a FileNotFoundException if I call the ctor with a fake path in the unit-test code.

How can I mock this code that I can verifiy whether the ContentId property was set correctly? I don't want to test the framework code.

bitsmuggler
  • 1,689
  • 2
  • 17
  • 30
  • Is that the entire test or are you injecting this attachment into another module you want to test? Because you really don't need to test .Net Framework code, just your own. – JMK Oct 28 '13 at 09:53
  • I understand that he wants to test the state of the Attachment.ContentId after his code under test has completed. – galenus Oct 28 '13 at 10:00
  • @galenus: Exactly - I want to test the state of the Attachment.ContentId – bitsmuggler Oct 28 '13 at 10:01
  • @JMK: Thank you for the answer. Yes it's the entire test. – bitsmuggler Oct 28 '13 at 10:05
  • 1
    I guess it's not really Attachment you want to mock then, it's actually the file system itself, there's some good answers [here](http://stackoverflow.com/q/1087351/969613). – JMK Oct 28 '13 at 10:14

1 Answers1

1

You don't have to use Moq for this, just use this constructor of the Attachment class, providing the stream you get from the resources of your testing project, and a matching ContentType. For example, you could add to resources some text file and specify the PlainText MIME type.

galenus
  • 2,087
  • 16
  • 24
  • Thank you for your answer - yes it's a way to go. But it's a pity, that I must call another ctor as a result of the testability. What do you think? – bitsmuggler Oct 28 '13 at 10:04
  • You can wrap any framework type in your own, adapting it to your needs, Attachment class among others. Your wrapper can have all virtual methods or it can implement an interface, both of these solutions will be mockable, leading to easier testing. But you have to decide the most pragmatic way for you to achieve the final result. So I don't think your current solution is an unacceptable one. – galenus Oct 28 '13 at 10:09