How to assert that a constructor calls a private method

2 posts, 1 answers
  1. Calvin
    Calvin avatar
    42 posts
    Member since:
    Jul 2011

    Posted 26 Mar 2012 Link to this post

    Is there a way to assert that a public constructor calls a private method?  As shown below, the PrivateMethod is internal so that the code will compile.  However, the assertion that PrivateMethod is called once fails because it's apparently called before the assertion is made.  Is there a way around this dilemma?  Secondly, I would like the PrivateMethod to be private (as the name suggests).  Is this possible?  THANKS!

    [Fact]
    void Test() {
        int p = 3;
        var m = Mock.Create<SUT>(p);
        Mock.Arrange(() => m.PrivateMethod(p)).OccursOnce();
        Mock.Assert(m);
    }
     
    public class SUT {
        public SUT(int p1) { PrivateMethod(p1); }
        internal void PrivateMethod(int p) { }
    }
  2. Answer
    Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 29 Mar 2012 Link to this post

    Hi Calvin,
    Thanks again for contacting us. Since you are calling the PrivateMethod in constructor which is raising the OnJITCompilationStarted event, therefore JM is unable to intercept it. Here to note that by design .net profiler can only intercept methods that are not already invoked. However, I wrote your test in the following way and things work as expected.

    static UnitTest1()
    {
        Mock.Partial<SUT>().For<SUT, int>((x, i) => x.PrivateMethod(i));
    }
     
    [TestMethod]
    public void Test()
    {
        int p = 3;
     
        var m = Mock.Create<SUT>(p);
     
        Mock.Arrange(() => m.PrivateMethod(p)).OccursOnce();
     
        m.PrivateMethod(p);
     
        Mock.Assert(m);
    }
     
    public class SUT
    {
        public SUT(int p1) { PrivateMethod(p1); }
        internal void PrivateMethod(int p) { }
    }

    Here i initialized the method in static block that is invoked in constructor so that the interceptor is already in place and calling the method in constructor does not affect the test.

    Secondly, yes you can mark the method as private as well. In that regard you have to mock it using the non public interface, more information on this can be found here :

    http://www.telerik.com/help/justmock/advanced-usage-mocking-non-public-members-and-types.html


    However, currently it is not possible to initialize non-public methods using Mock.Partial. I am creating a task for it in PITS which you can follow here:

    http://www.telerik.com/support/pits.aspx#/public/justmock/10526


    Kind Regards
    Mehfuz
    the Telerik team
    Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
  3. DevCraft R3 2016 release webinar banner
Back to Top