作者:佚名
原文链接: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());
}
写这类需要高关注度的伪造更简单和高效,使得我们的测试更简单和更加易读。不要高估你的依赖关系的复杂性,往往一个非常简单的伪造效果是最好的。