我是BDD集成测试的忠实粉丝,也开始考虑在单元测试中使用它们。从其他问题(例如,这一个1),我可以看到人们普遍认为编写BDD风格的单元测试是可以接受的。但是,我还没有看到任何使用BDD语言进行单元测试的例子。看到一些具体的例子会帮助我更好地理解它。使用BDD语言编写单元测试的好例子?
我想知道如何使用BDD,当测试正在检查用户不会遇到的低级系统行为。对于积分/视图测试,我会做这样的事情:
describe('Given that an author is using the question editor with a choice matrix question open ', function() {
describe('When the author clicks the 'Allow Multiple Responses' switch', function() {
it('Then the question preview should change from radio buttons to checkboxes', function() {
expect(....);
});
});
});
但什么,如果我测试低水平方法的功能?如果我试图测试用户永远不会碰它的低级单元,它是否为反模式?例如,如果我想用茉莉花来测试一个名为isCellShadedByAuthor()方法的功能,我最好的猜测是做这样的事情:
describe("Given that the cell is in the response area not on the author side", function() {
it("When the cell is an author shaded cell, then isCellShadedByAuthor should return true", function() {
expect(isCellShadedByAuthor(1, 3)).toBeTruthy();
});
));
我想另一种方式来处理这个情况,试图将测试提升到视图测试,根据CSS类的存在来断言,而不是直接声明isCellShadedByAuthor()的返回值。这会减少测试与实现细节的耦合。
例如,我可以做
describe("Given that the cell is in the response area not on the author side", function() {
it("When the user hovers over an author shaded cell, then the cell should have the hover class", function() {
var cell = $('shading-cell[data-attribute-x="1"][data-attribute-y="1"]);
expect(cell.hasClass('hover-disabled')).toBeTruthy();
});
));