如何更好地解耦我的数据层并限制我的单元测试范围? [英] How to decouple my data layer better and restrict the scope of my unit tests?

查看:15
本文介绍了如何更好地解耦我的数据层并限制我的单元测试范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在掌握单元测试并学习如何将我的代码分解成可测试的部分,但我不清楚的一件事是如何编写我的更高级别"代码,例如我的控制器操作,因此测试控制器不需要通过实际的数据层(在我的测试套件的其他地方独立测试).

I'm getting to grips with unit testing and learning how to break up my code into testable bits, but one thing I'm not clear on is how I can write my 'higher-level' code, such as my controller actions, so that testing the controller doesn't require going through the actual data layer (which is independently tested elsewhere in my test suite).

例如 - 我有一个用户验证,它需要一个用户名/密码并验证他们的帐户并返回登录成功/失败:

For example - I have a user validation which takes a username/password and validates their account and returns login success/failure:

class Api_AuthController extends Zend_Controller_Action
{
  public function validateUserAction()
  {
    // extract, clean and validate $username from POSTed data
    // extract, clean and validate $password from POSTed data

    // access the data layer
    $accountMapper = new Application_Model_Mapper_Account();
    $accounts = $accountMapper(find(array('username' => $username, 'password' => $password));

    if (count($accounts) == 1) {
      // success
    } else {
      // failure
    }
  }
}

如前所述 - Application_Model_Mapper_Account 和它的 find() 方法已经在另一个单元测试中测试过,所以它是多余的(据我了解单元测试 - 不受欢迎,不要提到它不必要地减慢了我的测试速度)在这里再次测试,因为我真正需要测试的是动作区分 find 函数的两种可能结果的能力.

As mentioned - Application_Model_Mapper_Account and its find() method have been tested in another unit test, so it's superfluous (and as I understand unit testing - undesirable, not to mention it's unnecessarily slowing down my tests) to test again here, as all I really need to test is the ability of the action to discriminate the two possible results of the find function.

那么 - 我如何将映射器和模型的模拟替换到此操作中,以便我可以限制 validateUserAction 测试的范围?

So - how do I substitute mocks for the mapper and model into this action so I can limit the scope of the validateUserAction tests?

推荐答案

我来自 .net 世界,但我们使用 控制容器反转以允许我们将任何依赖项注入控制器.通过这种方式,您可以模拟任何依赖项以按照您想要的方式运行,并将测试重点放在操作上.

I'm from the .net world, but we use Inversion of Control containers to allow us to inject any dependencies into the controller. This way you can mock any dependencies to behave how you want and focus your testing on the actions.

这篇关于如何更好地解耦我的数据层并限制我的单元测试范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆