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

Mocking Private Members

1 Answer 84 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Rob
Top achievements
Rank 1
Rob asked on 22 Apr 2011, 07:42 PM
 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.

1 Answer, 1 is accepted

Sort by
0
Ricky
Telerik team
answered on 27 Apr 2011, 03:27 PM
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
Tags
General Discussions
Asked by
Rob
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Share this question
or