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

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

1 Answer 71 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Rafia
Top achievements
Rank 1
Rafia asked on 08 Apr 2014, 05:36 AM
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

1 Answer, 1 is accepted

Sort by
0
Kaloyan
Telerik team
answered on 10 Apr 2014, 01:27 PM
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.

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