如何分离我的数据层更好,限制我的单元测试范围有多大? [英] How to decouple my data layer better and restrict the scope of my unit tests?

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

问题描述

我得到认真处理单元测试和学习如何打破我的code到可测试位,但有一件事我不是清楚的是我怎么能写我的'更高级别的'code,如我的控制器动作,使测试控制器不需要通过实际的数据层会(自主在我的测试套件其他测试)。

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

 类Api_AuthController扩展化Zend_Controller_Action
{
  公共职能validateUserAction()
  {
    //提取物,清洁和验证从发布的数据$用户名
    //提取物,干净,从发布的数据验证$密码    //访问数据层
    $ accountMapper =新Application_Model_Mapper_Account();
    $占= $ accountMapper(找到(阵列('用户名'= GT; $用户名,口令''= GT; $密码));    如果(计数($账户)== 1){
      //成功
    }其他{
      //失败
    }
  }
}

正如前面提到的 - Application_Model_Mapper_Account 找到()方法已经在另一个单元测试过测试,所以它是多余的(和我的理解单元测试 - 不可取的,更何况这是不必要的减慢我的测试),再次在这里测试,因为我真正需要测试的是行动歧视的查找功能的两种可能的结果的能力<。 / p>

所以 - 我怎么替换映射器与模型嘲笑这个动作,所以我可以限制validateUserAction测试范围


解决方案

我从.NET世界来的,但是我们用的控制容器的反转,以使我们能够注入任何依赖的到控制器。这样,您就可以模拟任何依赖关系的行为要如何和集中你的动作测试。

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
    }
  }
}

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.

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

解决方案

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天全站免登陆