Brendan Vogt
Brendan Vogt

Reputation: 26038

How to create a stub with Moq

How do I creat a pure stub using Moq? With Rhino Mocks I did it like this:

[TestFixture]
public class UrlHelperAssetExtensionsTests
{
     private HttpContextBase httpContextBaseStub;
     private RequestContext requestContext;
     private UrlHelper urlHelper;
     private string stylesheetPath = "/Assets/Stylesheets/{0}";

     [SetUp]
     public void SetUp()
     {
          httpContextBaseStub = MockRepository.GenerateStub<HttpContextBase>();
          requestContext = new RequestContext(httpContextBaseStub, new RouteData());
          urlHelper = new UrlHelper(requestContext);
     }

     [Test]
    public void PbeStylesheet_should_return_correct_path_of_stylesheet()
    {
        // Arrange
        string expected = stylesheetPath.FormatWith("stylesheet.css");

        // Act
        string actual = urlHelper.PbeStylesheet();

        // Assert
        Assert.AreEqual(expected, actual);
    }
}

How would I create a stub for MockRepository.GenerateStub<HttpContextBase>(); using Moq? Or should I just stay with Rhino Mocks?

Upvotes: 19

Views: 20696

Answers (3)

Digbyswift
Digbyswift

Reputation: 10410

A bit late to the party here but there's still not a sufficient answer here in my opinion.

Moq doesn't have explicit stub and mock generation in the same way RhinoMocks does. Instead, all setup calls, e.g. mockObject.Setup(x => blah ...) create a stub.

However, if you want the same code be treated as a mock, you need to call mockObject.Verify(x => blah ...) to assert that the setup ran as you expected.

If you call mockObject.VerifyAll(), it will treat everything you have setup as mocks and this is unlikely to be the behaviour you wish, i.e. all stubs treated as mocks.

Instead, when setting up the mock use the mockObject.Setup(x => blah ...).Verifiable() method to mark the setup explicitly as a mock. Then call mockObject.Verify() - this then only asserts the setups that have been marked with Verifiable().

Upvotes: 10

Fischermaen
Fischermaen

Reputation: 12468

Here is my suggestion for you:

Mock<HttpContextBase> mock = new Mock<HttpContextBase>();
mock.SetupAllProperties();

Then you have to do the setup.

For further informations see homepage of the MOQ project.

Upvotes: 17

Myles McDonnell
Myles McDonnell

Reputation: 13335

var mockHttpContext = new Mock<HttpContextBase>();

Upvotes: 0

Related Questions