Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 671
Brendan Vogt Avatar asked Nov 23 '11 12:11

Brendan Vogt


2 Answers

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.

like image 145
Fischermaen Avatar answered Sep 22 '22 15:09

Fischermaen


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().

like image 20
Digbyswift Avatar answered Sep 18 '22 15:09

Digbyswift