Moq, strict vs loose usage

前端 未结 4 620
盖世英雄少女心
盖世英雄少女心 2020-12-13 08:11

In the past, I have only used Rhino Mocks, with the typical strict mock. I am now working with Moq on a project and I am wondering about the proper usage.

Let\'s as

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 08:51

    I have a simple convention:

    1. Use strict mocks when the system under test (SUT) is delegating the call to the underlying mocked layer without really modifying or applying any business logic to the arguments passed to itself.

    2. Use loose mocks when the SUT applies business logic to the arguments passed to itself and passes on some derived/modified values to the mocked layer.

    For eg: Lets say we have database provider StudentDAL which has two methods:

    Data access interface looks something like below:

    public Student GetStudentById(int id);
    public IList GetStudents(int ageFilter, int classId);
    

    The implementation which consumes this DAL looks like below:

    public Student FindStudent(int id)
    {
       //StudentDAL dependency injected
       return StudentDAL.GetStudentById(id);
       //Use strict mock to test this
    }
    public IList GetStudentsForClass(StudentListRequest studentListRequest)
    {
      //StudentDAL dependency injected
      //age filter is derived from the request and then passed on to the underlying layer
      int ageFilter = DateTime.Now.Year - studentListRequest.DateOfBirthFilter.Year;
      return StudentDAL.GetStudents(ageFilter , studentListRequest.ClassId)
      //Use loose mock and use verify api of MOQ to make sure that the age filter is correctly passed on.
    
    }
    

提交回复
热议问题