假设我有几个Backbone模型,Rectangle和Triangle,每个都扩展了polygon.
var polygon = Backbone.Model.extend({ defaults: { width: 100,height: 100,rotation: 0 },rotate: function (degrees) { var oldRotation = this.get('rotation'); var newRotation = (oldRotation + degrees) % 360; this.set('rotation',newRotation); return newRotation; } }); var Rectangle = polygon.extend({ area: function (degrees) { return this.get('width') * this.get('height'); } }); var Triangle = polygon.extend({ area: function (degrees) { return this.get('width') * this.get('height') / 2; } }
我想测试Rectangle和Triangle并确保它们中的每一个都独立地实现正确旋转,即使我知道(现在)它们都从polygon继承了rotate的实现.
我不想做的是为Rectangle和Triangle创建单独的单元测试,它们几乎完全相互重复.在Mocha中,我如何编写旋转测试并在三角形和矩形的单元测试中重用它?
这是我的单元测试.请注意副本’旋转45度’测试.
describe('A rectangle',function () { var r = new Rectangle({width: 50,height: 10,rotation: 90}); it('correctly calculates its area',function () { expect(r.area()).to.equal(500); }); it('rotates by 45 degrees',function () { expect(r.rotate(45)).to.equal(135); }); }); describe('A triangle',function () { var t = new Triangle({width: 50,function () { expect(t.area()).to.equal(250); }); it('rotates by 45 degrees',function () { expect(t.rotate(45)).to.equal(135); }); });
解决方法
写完后答案很明显.我们可以创建一个函数来封装多边形的测试.
var describeApolygon = function (name,p) { describe(name,function () { it('rotates by 45 degrees',function () { expect(p.rotate(45)).to.equal(135); }); }); };
然后在Rectangle和Triangle的测试中使用它.
describe('A rectangle',function () { var r = new Rectangle({width: 50,rotation: 90}); describeApolygon('A rectangle',r); it('correctly calculates its area',function () { expect(r.area()).to.equal(500); }); }); describe('A triangle',function () { var t = new Triangle({width: 50,rotation: 90}); describeApolygon('A triangle',t); it('correctly calculates its area',function () { expect(t.area()).to.equal(250); }); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。