jim crown jim crown - 7 days ago 5
C# Question

Mocking a class with no interface or virtual methods

I want to test a method with following signature.

int SomeMethod(List<Employee> employees)


Here are the related classes

public class Employee
{
public int CustomerID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public Address Address { get; set; }

}

public class Address
{
public string StreetName { get; set; }
public string CityName { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
}


How can I create a moq object to mock List as an input to SomeMethod? Note that Employee and Address classes has no interface or virtual method.

Answer

If you want to test method with following signature int SomeMethod(List<Employee> employees) you don't need to mock Employee!

You need to create List<Employee> employees = new List<Employee>(), pass to method and verify result!

Employee and Address are models without any functionalities and you don't need to mock them!

Here are two thoughts about your case:

  1. You can legally call new Employee() or new Address() in your method because that code is testable! Creating new instances of models doesn't execute external dependency.

  2. It will be problem to call new Employee() or new Address() only if they have functionalities because in that case you will execute real dependency! Example, if Employee or Address communicate with database it is not testable, it will connect to real database when test is executed. Than you need to create mock to avoid database connection.