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

Call a private method in a test.

2 Answers 424 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
jwize
Top achievements
Rank 1
jwize asked on 19 Aug 2014, 09:40 AM
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 Answers, 1 is accepted

Sort by
0
jwize
Top achievements
Rank 1
answered on 19 Aug 2014, 10:35 AM
Figured it out

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

0
Todor
Telerik team
answered on 21 Aug 2014, 12:20 PM
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!

Regards,
Todor
Telerik
 

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.

 
Tags
General Discussions
Asked by
jwize
Top achievements
Rank 1
Answers by
jwize
Top achievements
Rank 1
Todor
Telerik team
Share this question
or