Mocking Private Members

2 posts, 0 answers
  1. Rob
    Rob avatar
    2 posts
    Member since:
    Apr 2011

    Posted 22 Apr 2011 Link to this post

     public class Class1
        {
            private bool Helper()
            {
                return true;
            }

            public bool TestMe()
            {
                if (Helper()) return true;

                return false;

            }

        }

     [TestMethod]
            public void TestMethod1()
            {

                var class1 = Mock.Create<Class1_Accessor>();
                Mock.Arrange(() => class1.Helper()).Returns(false);
                Mock.Arrange(() => class1.TestMe()).CallOriginal();
                bool actual = class1.TestMe();
                Assert.IsFalse(actual);

            }

    Why is the class1.Helper() mock not mocking, it is executing the method.  We have legacy code which has this going on everywhere so I want mock internal calls.

    Thanks.
  2. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 27 Apr 2011 Link to this post

    Hi Rob,
    Thanks again for reporting the issue. Here since you are mocking non-public member you need to use the non-public interface.

    Therefore, you could write the test in the following way that will make it work:

    [TestMethod]
    public void TestMethod1()
    {
        var class1 = new Class1();
        Mock.NonPublic.Arrange<bool>(class1, "Helper").Returns(false);
        bool actual = class1.TestMe();
        Assert.IsFalse(actual);
    }

    Note that you can here directly use the class reference for non-public members(partial mocking),  therefore no need to specify the extra CallOriginal for Testme().

    However, we found that if the target class is not sealed and you are doing Mock.Create , using the non-public interface it fails to resolve the method and thus fails the test. This is also resolved, so in that regard if partial mocking is not the solution for you and Mock.Create is a must, then you could additionally open a support ticket through which we will be happy to send you an internal build.

    Should you have any other issues please don't hesitate to write us back.

    Kind regards,
    Ricky
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  3. DevCraft R3 2016 release webinar banner
Back to Top