Mocking InnerException of SqlException does not work

2 posts, 1 answers
  1. Normen
    Normen avatar
    3 posts
    Member since:
    Aug 2012

    Posted 11 Sep 2012 Link to this post

    Hi there,
    I am trying to mock the InnerException-Property of a Mocked SqlException.

    [Test]
    public void SqlException_Example()
    {
        var sqlEx = Mock.Create<SqlException>();
        sqlEx.Arrange(ex => ex.Class).Returns(20);
        sqlEx.Arrange(ex => ex.InnerException).Returns(new Exception("My Test"));
     
        Assert.IsTrue(Mock.IsProfilerEnabled);
        Assert.That(sqlEx.Class, Is.EqualTo(20));
        Assert.That(sqlEx.InnerException, Is.Not.Null); //<-- Fails
    }


    I will be grateful for any help.

    Normen

  2. Answer
    Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 13 Sep 2012 Link to this post

    Hi Normen,
    Thanks again for contacting us.

    The property "InnerException" belongs to mscorlib. Therefore, you first need to initialize it. I did it in the following way and working as expected.

    static UnitTest1()
    {
        Mock.Replace<SqlException, Exception>(x => x.InnerException).In<UnitTest1>(x => x.TestMethod1());
    }
      
    [TestMethod]
    public void TestMethod1()
    {
        var sqlEx = Mock.Create<SqlException>();
        sqlEx.Arrange(ex => ex.Class).Returns(20);
        sqlEx.Arrange(ex => ex.InnerException).Returns(new Exception("My Test"));
      
        Assert.IsTrue(Mock.IsProfilerEnabled);
        Assert.AreEqual(sqlEx.Class, 20);
        Assert.IsNotNull(sqlEx.InnerException); //<-- works
    }

    For detailed information on mscorlib mocking please check out the following link:
    http://www.telerik.com/help/justmock/advanced-usage-mscorlib-mocking.html 


    Kind Regards,
    Ricky
    the Telerik team

    Time to cast your vote for Telerik! Tell DevPro Connections and Windows IT Pro why Telerik is your choice. Telerik is nominated in a total of 25 categories.

  3. DevCraft R3 2016 release webinar banner
Back to Top