简体   繁体   中英

How to handle methods that cannot be mocked during unit testing

I would like to know how we can handle methods that cannot be mocked while writing unit tests.

We have class called Students and it has a set of methods that are used to operate on the student data. And we also have some extensions methods(in C#) that are used for further processing. Now our business logic includes the use of methods of student class and extension methods.

Example:

class Student
{
    // fields
    filter()
    check()
    ...
}
BusinessLogic()
{
   // get list of students
   return students.Where(filter()).someExtensionMethod().FirstOrDefault().check();
}

Now if we want to test BusinessLogic method we cannot mock the methods filter(), check() and someExtensionMethod(). And if we go by regular approach we will setup test data such that we can test the output of each every methods and ensure that these methods are being called. It will be okay to do that if we have such 2 or 3 method calls. But I would like to know what to do in case when there many such method calls and the method involves complex logic which makes our test data setup more complex?

Edit: Here I am interested about functions that are defined in Student class. For example I have functions to check student has marks above 33. Like IsPass(). And I will call it like student.IsPass(). But the problem is in real project the number of such methods can be huge. And our business logic can be a combination of these methods

I would separate the logic that is responsible for retrieving student data in a separate class, eg " StudentRepository ". Then create an interface for this class and use it as dependency in your BusinessLogic.

public interface IStudentRepository
{
   IEnumerable<Student> GetStudents();
}

The implementation of IStudentRepository depends on your data store.

In the BusinessLogic class, you would have an "IStudentRepository" dependency:

public BusinessLogic(IStudentRepository studentRepository)
{
   // get list of students
   var students = studentRepository.GetStudents();

   // perform business logic on students

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM