Call a private method in a test.

3 posts, 0 answers
  1. jwize
    jwize avatar
    61 posts
    Member since:
    Mar 2013

    Posted 19 Aug 2014 Link to this post

    Can I (or does it make sense) call a private method from a unit test? 

    The setup code is getting really big to test a little piece of code within a private method. Instead it seems like it might be a good idea to just mock the parameters and then call the private method as follows (incomplete since I don't know if this works). I want to call a piece of the private implementation with defined parameters and then test for results. This would be a replacement for having to walk through the code in the debugger over and over again. 

    // Arrange mock data.
    var service = new ScheduledTaskService();
    var start = new DateTime(2014, 08, 15);
    var due = start.Next(DayOfWeek.Thursday);
    var assignee = new SimpleEmployeeView {Id = 1, LastNameFirstName = "Test User", IsActive = true};
    var taskModel = new ScheduledTaskModel()
        DaysBeforeDue = 5,
        Start = start,
        End = due,
        Title = "Test Subject",
        Description = "Test Description",
        Id = 999
    // This is the method I would like to call somehow if possible. 
    Mock.NonPublic.Arrange(service, "CreateTaskForAssignee", taskModel, assignee);
    // Ignore db changes. 
    var database = Mock.Create<Database>();
    Mock.Arrange(database, d => d.SaveChanges()).DoNothing();

    // TODO test for changes in the result.

  2. jwize
    jwize avatar
    61 posts
    Member since:
    Mar 2013

    Posted 19 Aug 2014 in reply to jwize Link to this post

    Figured it out

    // Act
    var instance = Mock.NonPublic.MakePrivateAccessor(service);
    instance.CallMethod("CreateTaskForAssignee", taskModel, assignee);

  3. Todor
    Todor avatar
    63 posts

    Posted 21 Aug 2014 Link to this post

    Hello Jaime,

    I confirm that this is the right API for mocking private members. If you need more assistance, do not hesitate to contact us!


    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

Back to Top