1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import java.util.Stack;

import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import static org.junit.Assert.*;

import annotations.Given;
import annotations.When;
import annotations.Then;

/**
 * Adaptation of http://www.jdave.org/examples.html
 */
@RunWith(SomeCustomBDDJUnit4Runner.class)
public class BDDStack {

	private Stack<String> stack;
	
	@Given("An empty Stack")
	public Stack<String> createNewStack() {
		stack = new Stack<String>();
		return stack;
	}
	
	// Could be in root class too
	class Unmodified {
		@Then("Stack is empty")
		void shouldBeEmpty() {
			assertTrue(stack.isEmpty());
		}
	}
	
	class Modified {
		@When("$string is pushed to stack")
		void shouldPushToStack(String item) {
			stack.push(item);
		}
		
		@Then("Stack shouldn't be empty")
		void shouldNotBeEmpty() {
			assertFalse(stack.isEmpty());
		}
	}
	
	class Full {
		@When("Stack is filled to capacity")
		void shouldBeFilled() {
			for (int i=0; i<stack.capacity(); i++) {
				stack.push("item " + i);
			}
		}
		
		@Then("Stack is full")
		void shouldBeFull() {
			assertTrue(stack.size() == stack.capacity());
		}
		
		@Then("Stack can't be modified")
		void shouldBeUnmodifiable() {
			try {
				stack.add("another");
				fail("Should've thrown exception");
			} catch (RuntimeException e) {}
		}
		
		@Then("Stack contains all added items")
		void shouldContainItems() {
			for (int i=0; i<stack.capacity(); i++) {
				assertTrue(stack.contains("item " + i));
			}
		}
		
		@Then("Doesn't contain removed item")
		void shouldNotContainRemovedItem() {
			stack.remove("item 3");
			assertFalse(stack.contains("item 3"));
		}
	}
	
	class PartlyFilled {
		@When("Stack is filled partly")
		void shouldFillStackPartly() {
			stack.push("one");
			stack.push("two");
			stack.push("three");
		}
		
		@Then("Push should add new item to top of the stack")
		void shouldAddToTop() {
			stack.push("on top");
			assertEquals("on top", stack.peek());
		}
	}
}


// Run report would look something like this:

"Given an empty stack"
	"Then stack is empty"

	"When item is pushed to stack"
		"Then stack shouldn't be empty"

	"When stack is filled to capacity"
		"Then stack is full"
		"Then stack can't be modified"
		"Then stack contains all added items"
		"Then stack doesn't contain removed item"

	"When stack is filled partly"
		"Then push should add new item to top of the stack"