How Mock Protected Methods?? Mock.NonPublic not working for Protected methods

2 posts, 0 answers
  1. Rafia
    Rafia avatar
    2 posts
    Member since:
    Apr 2014

    Posted 08 Apr 2014 Link to this post

    Public  class Baseclass{

    protected void Setting (int y) {
    y=10;

     }
    }

    public class ChildClass :Baseclass{

    public void setvalue (int x){
    Setting(x);
    }
    }

    How we mock Setting method of Base Class ??
    Mock.NonPublic.Arrange(new Baseclass() , "Setting", ArgExpr.IsAny<int>()).DoNothing();  //  Mock.NonPublic not working for Protected methods
  2. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 10 Apr 2014 Link to this post

    Hi Rafia,

    Thank you for contacting.

    There are several possible approaches for this. Let's assume we have the following system under test:
    public  class Baseclass
    {
        protected void Setting (int y)
        {
            throw new NotImplementedException();
        }
    }
     
    public class ChildClass :Baseclass
    {
        public void setvalue (int x)
        {
            Setting(x);
        }
    }
    , where the Setting function is protected. Now, to mock it we need an actual instance either of the Baseclass or of the ChildClass (as it inherits the Baseclass). Here are both the options:
    [TestMethod]
    public void Option1()
    {
        var childaclassMock = new ChildClass();
     
        Mock.NonPublic.Arrange(childaclassMock, "Setting", ArgExpr.IsAny<int>()).DoNothing();
     
        childaclassMock.setvalue(5);
    }
     
    [TestMethod]
    public void Option2()
    {
        var baseclassMock = new Baseclass();
     
        Mock.NonPublic.Arrange(baseclassMock, "Setting", ArgExpr.IsAny<int>()).IgnoreInstance().DoNothing();
     
        var child = new ChildClass();
        child.setvalue(5);
    }
    Note that, the second option uses Future Mocking, while the first directly intercepts the Setting call from within your Childclass. More about Mocking Non-public Members and Types.

    I hope this helps.

    Regards,
    Kaloyan
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  3. DevCraft R3 2016 release webinar banner
Back to Top