The right way to use MOQ setup and returns

前端 未结 1 1084
死守一世寂寞
死守一世寂寞 2020-12-21 11:21

Im new to MOQ and I am a little confused with the setup method. The example below shows one method that i need to test. The method under test returns the latest time from tw

相关标签:
1条回答
  • 2020-12-21 11:42

    You use Moq in a wrong way. It is intended to substitute some implementations your tested class is dependent on. For example, you are testing some class which uses a DB repository:

    public class MyService
    {
        private IMyDbRepository _repos;
    
        public MyService(IMyDbRepository dbRepos)
        {
            _repos = dbRepos;
        }
    
        public string[] GetClientNames()
        {
            return _repos.GetAllClients().Where(c=>!c.IsDisabled).OrderBy(c=>c.Name).ToArray();
        }
    }
    

    You need to test the GetClientNames() method. But you can't until you have IMyDbRepository instance. It's too complicated and wrong to create and fill database just to test method of sorting and filtering clients.

    The way out is to use Moq:

    [Test]
    public void TestGetAllClientsDoesNotReturnDisabledUsers()
    {
        var dbReposMock = new Mock<IMyDbRepository>();
        dbReposMock.Setup(r=>r.GetAllClients()).Returns(
                          new []{ new Client { Name="AAA", IsDisabled=true },
                                  new Client { Name="BBB", IsDisabled=false } });
    
        var myTestingService = new MyService(dbReposMock.Object);//You pass here the autogenerated object which follows the described primitive behavior without requiring DB at all.
        var clientNames = myTestingService.GetClientNames();
        Assert.AreEqual(1, clientNames.Length);
        Assert.AreEqual("BBB", clientNames[0]);
    }
    

    So Moq allows you generating fake class (non-sealed) or interface implementations on the fly (in runtime) and use then to decouple your testing functionality from everything else. Consequently if bug appears in the DB structure, you see only few DB-tests failing and can easily identify what is the problem comparing to the case when 100 different tests from all layers failing if you didn't decouple the code with Moq.

    0 讨论(0)
提交回复
热议问题