让你的伪造保持简单

作者:佚名

原文链接:http://googletesting.blogspot.tw/2009/01/tott-keep-your-fakes-simple.html


当加利福尼亚的科学家想囚禁饲养秃鹰时遇到了一个问题。雏鸟不会从研究员手中吃食;它们需要它们的妈妈喂养它们。所以科学家拿了一个木偶,对于雏鸟来说,喂养它们的就像是它们的妈妈,但是在娃娃里实际是科学家的手。

基于以下思考一个人造的例子:

TEST_F(BabyCondorTest,EatsCarrion) {
  FakeCondormother;
  scoped_ptr carrion;
  BabyCondor*pchick = &chick_;
  mother.Imprint(vector(&pchick,&pchick + 1)); // just one chick
  while(!chick_.HasFood()){
    mother.Eat();// disposes of any food the mother kept for herself
    mother.Scavenge(carrion.reset(newFakeCarrion)); // finds new food
    mother.RandomlyDistributeFoodAmongYoungAndSelf();// feeds baby or mom
  }
  chick_.Eat();
  EXPECT_TRUE(carrion->WasEaten());
}

有些东西是错误的-这里存在大量的设置!通用的类FakeCondor从完整类复制了太多的功能。科学家的木偶没有以腐肉为食,所以为什么我们要?我们只是想测试子类Eats。我们集合了各种母性行为,例如给食物,单个方法通过抽象一个角色类调用。(如果我们不能改变Condor,我们也会写一个适配器。)

class CondorMotherhoodRoleInterface{
 public:
  virtualCarrion* GiveFood() = 0;
  virtualSomeReturnTypes* OtherMomBehaviors() = 0;
};

我们写一个一次性的伪造仅仅提供给我们特殊的测试行为

class CondorFeedingPuppet: publicCondorMotherhoodRoleInterface {
 public:
  virtualCarrion* GiveFood() { return test_carrion_; }
  virtualSomeReturnTypes* OtherMomBehaviors() { return NULL; } 
  Carrion*test_carrion_; // public var is tolerable in a one-off object
};

TEST_F(BabyCondorTest,EatsCarrion) {
  CondorFeedingPuppetmother; FakeCarrion test_carrion;
  mother.test_carrion_= &test_carrion;
  chick_.ReceiveFood(&mother);
  chick_.Eat();
  EXPECT_TRUE(test_carrion.WasEaten());
}

写这类需要高关注度的伪造更简单和高效,使得我们的测试更简单和更加易读。不要高估你的依赖关系的复杂性,往往一个非常简单的伪造效果是最好的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值