This is a migrated thread and some comments may be shown as answers.

How to assert that a constructor calls a private method

1 Answer 106 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Calvin
Top achievements
Rank 2
Calvin asked on 26 Mar 2012, 07:01 PM
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) { }
}

1 Answer, 1 is accepted

Sort by
0
Accepted
Ricky
Telerik team
answered on 29 Mar 2012, 07:00 PM
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 >>
Tags
General Discussions
Asked by
Calvin
Top achievements
Rank 2
Answers by
Ricky
Telerik team
Share this question
or