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

Non-public methods not mocked

1 Answer 50 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Alex
Top achievements
Rank 1
Alex asked on 24 Aug 2012, 08:33 PM
This scenario unexpectedly throws "shouldn't be here" exception which means methods are not mocked out.  As soon as you change method access from protected to public, all works as expected.  It seems that only public methods get mocked out.  Is this by design?  I would expect all methods to be mocked out unless I specify Behavior.CallOriginal.

public class Test1
{
    protected void Testing1()
    {
        string s = "Testing1";
        throw new Exception("shouldn't be here");
    }
}
 
public class Test2 : Test1
{
    protected void Testing2()
    {
        Testing1();
        string s = "Testing2";
        throw new Exception("shouldn't be here");
    }
}
 
public class Test3 : Test2
{
    protected void Testing3()
    {
        Testing1();
        Testing2();
        string s = "Testing3";
    }
}
 
 
    [Test]
    public void MakeSureAllMethodsAreMockedOut()
    {
        Test3 test3 = Mock.Create<Test3>();
 
        Mock.NonPublic.Arrange(test3, "Testing3").CallOriginal().MustBeCalled();
 
        test3.GetType().GetMethod("Testing3", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Invoke(test3, new object[] { });
    }
Here's simplified setup that also fails for the test above:
public class Test3
{
    protected void Testing1()
    {
        string s = "Testing1";
        throw new Exception("shouldn't be here");
    }
 
    public void Testing3()
    {
        Testing1();
        string s = "Testing3";
    }
}

1 Answer, 1 is accepted

Sort by
0
Ricky
Telerik team
answered on 27 Aug 2012, 08:55 PM
Hi Alex,
Thanks again for contacting us.

If you mock a class using Mock.Create by default it should mock all the public members. Generally, it leaves out the private ones as in most cases that lead to an increased performance while executing the tests. So your test will work just fine, if you do this:

[Test]
public void MakeSureAllMethodsAreMockedOut()
{
    Test3 test3 = Mock.Create<Test3>();
 
    Mock.NonPublic.Arrange(test3, "Testing1").DoNothing();
    Mock.NonPublic.Arrange(test3, "Testing2").DoNothing();
 
    Mock.NonPublic.Arrange(test3, "Testing3").CallOriginal().MustBeCalled();
 
    test3.GetType().GetMethod("Testing3", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Invoke(test3, new object[] { });
}

In short, JustMock is designed to mock non-public methods when needed.


Kind Regards
Mehfuz
the Telerik team

Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Tags
General Discussions
Asked by
Alex
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Share this question
or