This is a migrated thread and some comments may be shown as answers.

Mocking a non-virtual instance method across instances

3 Answers 71 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Asim Imam
Top achievements
Rank 1
Asim Imam asked on 14 Jul 2011, 09:36 PM
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?

3 Answers, 1 is accepted

Sort by
0
Ricky
Telerik team
answered on 19 Jul 2011, 12:07 PM
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!

0
Matt Kalai
Top achievements
Rank 1
answered on 20 Nov 2011, 06:47 PM
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. 
1
Ricky
Telerik team
answered on 21 Nov 2011, 08:36 AM
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 >>

Tags
General Discussions
Asked by
Asim Imam
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Matt Kalai
Top achievements
Rank 1
Share this question
or