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
My (legacy) MVC application has the following hierarchy of controller classes:


public class CMSController : BaseController
{
        public virtual void SetModelValues(ModelBase model)
        {
            model.CurrentPageURL = Request.Url.ToString();
            // set more model data...
        }

}


public class PageController : CMSController 
{
        public ActionResult Index()
        {
            MyModel model = new MyModel();
            base.SetModelValues(model);
            ViewBag.Title = "My Title";
            return View(model);
        }
}



I am writing unit tests for the PageController.Index method.
I am trying to Fake the call to base.SetModelValues, so that it is not invoked, but can not get this to work.


    var fake = Isolate.Fake.Instance<CMSController>();
    Isolate.Swap.AllInstances<CMSController>().With(fake );
    Isolate.WhenCalled(() => fake.SetModelValues(null)).WillThrow(new Exception("my exception"));

    // Creating an instance of PageController
    PageController _controller = new PageController();

    // Call the index method
    var result = _controller.Index() as ViewResult;

    Assert.IsNotNull(result);

When I run my test however, the actual base.someVirtualMethod still gets invoked.
Can I declare a Fake (or Mock?) in my test which will prevent the real base.someVirtualMethod from running?
asked by (3.1k points)

1 Answer

0 votes
Hi rob,

Please look at this example that demonstrate how to prevent base class methods from being called.


    class GrandParent
    {

    }

 
    class Parent : GrandParent
    {
        public virtual void CallMe()
        {
            throw new Exception();
        }

    }

    class Child : Parent
    {
        public void Index()
        {
            Console.WriteLine("Before");
            base.CallMe();
            Console.WriteLine("After");
        }
    }




        [TestMethod]
        public void MethodUnderTest()
        {

            Child c = new Child();

            Isolate.WhenCalled(() => c.CallMe()).IgnoreCall();

            c.Index();
        }





Let me know if it helps
answered by (4k points)
...