Mocking a non-virtual instance method across instances

4 posts, 0 answers
  1. Asim Imam
    Asim Imam avatar
    1 posts
    Member since:
    Oct 2009

    Posted 14 Jul 2011 Link to this post

    Hi!

    Please consider the case when the method I want to test looks like this:

    public class Foo {
        public void TestMe(<arg list>)
        {
            [business logic omitted...]

             Helper hlp = new Helper();
             bool wasHelped = hlp.HelpMe(<arg list>);   

            [business logic omitted...]
        }
    }

    Since the object "hlp" is initialized within the method that's to be tested, as opposed to being instantiated by the test method, will JustMock allow mocking the (non-virtual, non-static) method "Helper.HelpMe" such that the above call to "HelpMe" is re-routed to the mocked implementation? If so, what would be the syntax for doing this?

  2. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 19 Jul 2011 Link to this post

    Hi Asim,

    Thanks again for reaching us.

    Yes you can mock the above scenario with JustMock. I am attaching a project that mocks the HelpMe method to return a certain value instead executing it that on the other hand throws exception. Please note that this is a commercial feature and not available in the free edition.



    Kind Regards,
    Mehfuz
    the Telerik team

    Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

  3. DevCraft R3 2016 release webinar banner
  4. Matt Kalai
    Matt Kalai avatar
    1 posts
    Member since:
    May 2010

    Posted 20 Nov 2011 Link to this post

    Test method does not use created mock.  The dependency is not removed. I believe that you mist injecting mock up into the class under the test. 
  5. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 21 Nov 2011 Link to this post

    Hi Matt,

    Thanks again for the suggestion. However, in JustMock we have a feature called partial mocking and it is also possible to ignore instance for a specific setup.

    Therefore, I can easily do :

    var helper = new Helper();
     
    Mock.Arrange(() => helper.HelpMe(Arg.AnyInt)).Returns(true).IgnoreInstance();
     
    new Foo().TestMe(10)

    Here the TestMe method looks like:

    public void TestMe(int arg1)
    {
        Helper hlp = new Helper();
        bool wasHelped = hlp.HelpMe(arg1);
    }


    Therefore, you can easily mock a method without ever passing the dependency.



    Kind regards,
    Mehfuz
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

Back to Top