Mocking abstract class results in AccessViolationException.

4 posts, 0 answers
  1. Geert
    Geert avatar
    2 posts
    Member since:
    Jan 2012

    Posted 24 Jan 2012 Link to this post

    Hi all,

    I have the following class (simplified)

    public abstract class AbstractStateMachine
    {
          public void DoClose()
          {
            //do something
             close();
          }
          public abstract void close();
    }

    I want to test if the close() method is called, so I thought I could do the following:
    [TestMethod]
    public void TestMethod1()
    {
        AbstractStateMachine sm = Mock.Create<AbstractStateMachine>(Behavior.CallOriginal);
        Mock.Arrange(() => sm.close()).DoNothing().MustBeCalled();
        sm.DoClose();
    }

    As a result, I get a AccessViolationException in the sm.DoClose() method.
    What am I doing wrong?

  2. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 25 Jan 2012 Link to this post

    Hi Geert,

    Thanks again for contacting us. You are getting access violation exception because DoClose is a private method and you are trying to access it directly from test method using sm.DoClose(). However, you can write it in the following way and the test will work as expected:
    AbstractStateMachine sm = Mock.Create<AbstractStateMachine>(Behavior.CallOriginal);
     
    Mock.Arrange(() => sm.close()).DoNothing().MustBeCalled();
     
    sm.close();
     
    Mock.Assert(sm);


    Hope this solves your issue.

    Kind regards,
    Mehfuz
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

  3. DevCraft R3 2016 release webinar banner
  4. Geert
    Geert avatar
    2 posts
    Member since:
    Jan 2012

    Posted 25 Jan 2012 Link to this post

    Hi there,

    Sorry, that was a typo in my original mail. The DoClose() was a public method in my original code. The whole idea was to do partial mocking, i.e. only mock the abstract functions of my abstract base class.

    I switched to Moq (using CallBase=true), and everything works fluently there.
  5. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 26 Jan 2012 Link to this post

    Hi Geert,

    Thanks again for your reply. I have tried the test with public DoClose method and its working as well. I have also attached the test project to let you have a look.

    In addition, please make sure that you are using the latest build. You can easily get one from NuGet with using install-package JustMock command.

    Kind Regards,
    Mehfuz
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

Back to Top