我是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();
});
));