现在,让我们来看看“hello world”风格的Cucumber的小例子。Cucumber测试是以扩展名为feature的纯文本文件实现的,看上去像下面这样:
Feature: Addition
I would like to add numbers with my pocket calculator
Scenario: Integer numbers
* I have entered 4 into the calculator
* I press add
* I have entered 2 into the calculator
* I press equal
* The result should be 6 0n the screen
feature的描述与实现语言无关。Cucumber测试代码的描述是通过名为Gherkin的词表完成的。
如果你用的是Java 8 lambda版本的Cucumber,测试的一个步骤看起来像会像下面这样
Calculator calc;
public MyStepdef s ( ) {
Given ( "I have entered (\d+) into the calculator", (Integer i) ->
System. out . format ( "Number entered: n ", i) ;
calc.push (i) ;
});
When ("I press (\W+) ", (String op) -> {
System. out . format ( "operator entered: %n ", op) ;
calc.op (op) ;
});
Then ("The result should be (\d+) ", (Integer i) ->
System.out . format ( " result : n ", i) ;
assertThat (calc.result(),i)j
));
和以前一样,你可以在本书源码包中找到完整的代码。
这只是一个简单的例子,但它可以立刻能展现出Cucumber的长处和短处。feature的描述可读性很好。但是你必须在测试代码中使用正则表达式来匹配字符串。即使只是微调feature描述,你也需要去调整测试代码。