chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!
0 votes
Is it possible to mock a protected field in a base class when testing a derived method?

Here's a sample. I want to test Foo() method, but wish to ingore the calls to the protected field "log". Currently it throws an null exception.

I'm guess that the base class isnt created like normal when mocking? I cant find much documentation on how class hierarchies are handled.

   public interface ILog
    {
        void Debug(string s);
    }

    public class Logger : ILog
    {
        public void Debug(string s)
        {
        }
    }

    public abstract class AbstractBaseClass
    {
        protected ILog log = new Logger();
    }

    public class BaseClassA : AbstractBaseClass
    {        
    }

    public class BaseClassB : BaseClassA
    {
        protected string Foo()
        {
            log.Debug("test"); // How do I mock this call??

            return "abc";
        }        
    }

    [TestClass]
    public class UnitTest3
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mockB = Isolate.Fake.Instance<BaseClassB>();
            Isolate.NonPublic.WhenCalled(mockB, "Foo").CallOriginal();

            string s = Isolate.Invoke.Method(mockB, "Foo") as string;

            Assert.IsNotNull(s);
            Assert.AreEqual(s, "abc");
        }
    }
asked by (3.2k points)

1 Answer

0 votes
Figured it out :D

var mockB = Isolate.Fake.Instance<BaseClassB>(Members.ReturnRecursiveFakes,ConstructorWillBe.Called);
answered by (3.2k points)
...