Return to site

🥒☕ CUCUMBER or BDD with Java

· java,testing

I just finished a course on Behavior Driven Development with Cucumber.

👩 🏫 Behavior-driven development (BDD) is an Agile software development methodology in which an application is documented and designed around the behavior a user expects to experience when interacting with it.

So concretely, in my code, I have gherkin statements that explain the test in plain English, then it is mapped in Java code.

Gherkin👇

Feature: the joke can be retrieved
  Scenario: client makes call to GET /jokes
    Given the app calls /jokes
    When the client call the app
    Then the client receives status code of 200
    And the client receives server joke "Moving to Paris would be In-Seine."

Java step definitions (that mapped this gherkin above)👇

@Given("^the app calls /jokes$")
public void remoteCallOfExternalJokeApiByApp() throws Throwable {
    wireMockServer.stubFor(get(urlEqualTo("/onlinejokes")).willReturn(aResponse().withBody("""
            {
                "id":"1",
                "content": "Moving to Paris would be In-Seine."
              }
            """)));
}

@When("^the client call the app$")
public void frontCallOfOurAppByClient() throws Throwable {
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(DUMMY_LOCAL_JOKE_URL);
    builder.accept(MediaType.APPLICATION_JSON);
    try {
        log.error("vv in the when setting the current action");
        context().setCurrentAction(this.mockMvc.perform(builder));
    } catch (Exception e) {
        log.error("VV error in when:" + e.getMessage());
        context().setCurrentException(e);
    }
}

@Then("^the client receives status code of (\\d+)$")
public void checkCallStatus(int statusCode) throws Throwable {
    log.error("vv in the then getting the current action");
    context().getCurrentAction().andExpect(status().is(statusCode));
}

@And("^the client receives server joke (.+)$")
public void checkCallBody(String joke) throws Throwable {
    log.error("vv in the and getting the current action");
    context().getCurrentAction().andExpect(content().json("""
            {
                "id":"1",
                "content": "Moving to Paris would be In-Seine."
              }
            """));
}

In the end, we got a little story 📖 in English that anybody can understand (completely agnostic of programming👨 💻❌) with the three words: Given/When/Then.

Happy (agile) coding! 🙂

Check below a POC on my GitHub doing a BDD for a GET👇