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 Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
I'm trialing the product and im also very new to mocking frameworks. Below is a simple example of something I'm trying to acheive in a much bigger project.

I'm trying to write a unit test for the protected method in an abstract class. I was hoping that the below code would inject a mock "Search" interface object that I had arrange to return a know value. But it doesnt!

What have I missed? Note: I actually want the code instead BaseClass.GetString to execute (that's the test) but I want the Search interface it uses to be a mock.

    public interface ISearch
    {
        string GetString(int type);
    }

    public abstract class BaseClass
    {
        public ISearch Search { get; set; }

        protected string GetString(int type)
        {
            return Search.GetString(type);
        }
    }

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mock = Isolate.Fake.Instance<BaseClass>();

            Isolate.WhenCalled(() => mock.Search.GetString(1)).WithExactArguments().WillReturn("one");

            string s = Isolate.Invoke.Method(mock, "GetString", 1) as string;

            Isolate.Verify.WasCalledWithExactArguments(() => mock.Search.GetString(1));
            
            Assert.IsNotNull(s);
            Assert.Equals(s, "one");
        }
    }
asked by solidstore (3.2k points)

1 Answer

0 votes
Hello,

If I understand you correctly, you want to call the original implementation of "GetString" on the abstract class. In order to do that, you need to instruct the mock object to do it, by adding the following line after creating a fake instance:

Isolate.NonPublic.WhenCalled(mock, "GetString").CallOriginal();


Also, you should use Assert.AreEqual instead of Equals to test the value of the string.

Hope that helps.
answered by igal (5.7k points)
...