Skip to content

Instantly share code, notes, and snippets.

@mike-hogan
Created February 24, 2017 11:16
Show Gist options
  • Save mike-hogan/ced18517802f76cf950dab286b5fc992 to your computer and use it in GitHub Desktop.
Save mike-hogan/ced18517802f76cf950dab286b5fc992 to your computer and use it in GitHub Desktop.
How to get given,when,then with interesting givens and inputs and outputs with Yatspec
package learning.yatspec;
import com.googlecode.yatspec.junit.SpecRunner;
import com.googlecode.yatspec.state.givenwhenthen.*;
import org.eclipse.jetty.http.HttpStatus;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.eclipse.jetty.http.HttpStatus.Code.OK;
import static org.hamcrest.core.Is.is;
@RunWith(SpecRunner.class)
public class GivenWhenThenYatspec implements WithTestState{
private TestState testState = new TestState();
@Test
public void reallySimpleExample() throws Exception {
given(theSystemIsRunning());
and(theDatabaseIsEmpty());
when(theUserSubmits(aValidCreateQuoteRequest()));
then(theReturnedResponse(), is(OK));
thenAlso(theQuoteDatabase(), hasAQuoteRecorded());
}
private TestState when(ActionUnderTest aut) throws Exception {
return testState().when(aut);
}
private StateExtractor<String> theQuoteDatabase() {
//you should really interrogate the database here to get some assertable value
return inputAndOutputs -> "thedatabase";
}
private <T> TestState then(StateExtractor<T> s, Matcher<T> m) throws Exception {
return testState.then(s, m);
}
private <T> TestState thenAlso(StateExtractor<T> s, Matcher<T> m) throws Exception {
return then(s, m);
}
private Matcher<String> hasAQuoteRecorded() {
//this should be an assert against the assertable database returned from theQuoteDatabase()
return is("thedatabase");
}
private StateExtractor<HttpStatus.Code> theReturnedResponse() {
return inputAndOutputs -> OK;
}
private ActionUnderTest theUserSubmits(String request) {
//send the request to the system here
return (givens, capturedInputAndOutputs) -> capturedInputAndOutputs.add("the request", request);
}
private String aValidCreateQuoteRequest() {
return "some json";
}
private GivensBuilder theDatabaseIsEmpty() {
//empty the database here
testState().interestingGivens.add("Number of quotes in database",0);
return g -> g;
}
private GivensBuilder theSystemIsRunning() {
//bring up the system or assert it's running
testState().interestingGivens.add("Service A","Running on http://localhost:8080/service-a using build 97345");
testState().interestingGivens.add("Service B","Running on http://localhost:8080/service-b using build 243");
return givens -> givens;
}
private TestState given(GivensBuilder gb) throws Exception {
return testState().given(gb);
}
private TestState and(GivensBuilder gb) throws Exception {
return testState().and(gb);
}
@Override
public TestState testState() {
return testState;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment