How to create a stub with Moq

Brendan Vogt picture Brendan Vogt · Nov 23, 2011 · Viewed 16.2k times · Source

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?

Answer

Fischermaen picture Fischermaen · Nov 23, 2011

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.