views:

381

answers:

1

I'm new to mocking so I need a bit of guidance on how to mock HttpPostedFileBase with Rhino Mocks. I am trying to verify that my ToByteArray() extension works as expected and this is what I have so far:

[Test]
 public void Should_return_a_byte_array_with_a_length_of_eleven()
 {
  // Arrange
  var stream = new MemoryStream(System.Text.Encoding.Default.GetBytes("TestContent"));
  var httpPostedFileBase = MockRepository.GenerateMock<HttpPostedFileBase>();

  httpPostedFileBase.Expect(x => x.InputStream).Return(stream);
  httpPostedFileBase.Expect(x => x.ContentLength).Return(11);

  // Act
  var byteArray = httpPostedFileBase.ToByteArray();

  // Assert
  Assert.That(byteArray.Length, Is.EqualTo(11));
 }

I can tell that the values get set but by the time my extensionmethod gets the HttpPostedFileBase it has lost all it's values. Any help would be much appreciated.

/ Kristoffer

+1  A: 

Whenever possible, you should avoid mocking in order to verify that your implementation is what you expect. Instead, favor testing that for some particular input, the output is what you expect.

That said, your example is missing a few key things. When you use mocks, you need to tell them when you're done setting up the expectations (otherwise they will record all method calls and suchlike as further expectations) by calling:

httpPostedFileBase.Replay();

And finally at the assert stage, verify your expectations with:

httpPostedFileBase.VerifyAllExpectations();

Also note that with Rhino, you can only mock methods and properties that are virtual.

Rytmis
Thanks for your reply!I tried this but I'm still getting "Expected: 11 But was: 0". I put Replay() before I call ToByteArray() and VerifyAllExpectations() after ToByteArray().I've heard your argument about mocking before but I'm not sure I undestand how I could verify this in another way. How would you have done it?
Kristoffer Ahl
I got your suggestions working after setting Repeat.Any() on my expectations.However, I'm still interested in how you could have done it differently!?
Kristoffer Ahl
If you could construct an actual instance of HttpPostedFile (or some derivation of HttpPostedFileBase) with some test content, you could just call the extension method on that. But I don't know the HttpPostedFile class well enough to be 100% sure it is possible.
Rytmis
The point of the argument is that when you set up a lot of expectations, you're specifying the implementation of the method in high detail, when what you really want to do is verify the contract of your method.
Rytmis
Thanks! That was my original intention but I was unable to create an instance of HttpPostedFile and HttpPostedFileBase so that's why I ended up doing it with mocking.
Kristoffer Ahl