1
votes

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

1 Answers

2
votes

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.