BDDの実践
今回実装する例は、従業員名簿クラスです。名簿リストへの名前の追加と、追加された名前を一覧する機能を実装します。
JBehaveでは、検証のシナリオをGiven、When、Thenという3つの観点から記述します。それぞれに以下のような意味があります。
- Given:振る舞いの起動前の状態
- When:実際に起動したい振る舞い
- Then:振る舞いの起動によって何が変化したか
storyファイルにシナリオを記述し、これを軸にして以後の作業を進めます。今回の例の場合、以下のように記述します。
Scenario: 従業員名簿に名前を一件追加します Given 空の従業員名簿を作成します When <name>を追加します Then <name>が追加されていること Examples: |name| |徳川家康|
<name>というのがパラメータであり、Examples以下にパラメータの例を記述します。
この内容を「payroll_stories.story」というファイル名で用意し、「src/test/resouces」以下の「com.example」パッケージに配置します。
次に、Storiesクラスを作成します。storyファイルを読み込み、テストを行うために必要になるクラスです。以下のように実装します。
package com.example;
import static org.jbehave.core.reporters.Format.CONSOLE;
import static org.jbehave.core.reporters.Format.TXT;
import java.util.Arrays;
import java.util.List;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
public class PayRollStories extends JUnitStories {
@Override
public Configuration configuration() {
return super.configuration().useStoryReporterBuilder(
new StoryReporterBuilder().withDefaultFormats().withFormats(
CONSOLE, TXT)); ・・・(1)
}
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new AddPayRollSteps());・・・(2)
}
@Override
protected List storyPaths() {
return Arrays.asList("com/example/payroll_stories.story"); ・・・(3)
}
}
- コンソールにテスト結果を詳細に表示するための設定です。
- 実行するステップを指定します(ステップについは以降で説明)。
- 実行するstoryファイルを指定します。
次にStepクラスを実装します。Stepクラスとは、xUnitでのテストクラスとほぼ同じ役割を持ったクラスです。テストの事前準備、振舞の起動、事後検証について実装します。以下のようにGiven、When、Thenのそれぞれのフェーズに分けて処理を実装します。
package com.example;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
public class AddPayRollSteps {
@Given("空の従業員名簿を作成します")
public void givenAPayRoll() {
}
@When("<name>を追加します")
public void whenRegister(@Named("name")String name) {
}
@Then("<name>が追加されていること")
public void thenTheContainsShould(@Named("name")String name) {
}
}
Given、When、Thenアノテーションに指定する文字列は、それぞれstoryファイルに記述した文字列と一致させます。Namedアノテーションに指定する文字列は、storyファイルに記述したパラメータの名前と一致させます。以上の2つのクラスを「src/test/java」の「com.example」パッケージへ配置します。
