Ping Service For Springboot Project

For the plain Vanila Spring boot project that we created, I will create a Ping Service. This service can be later used to check if the host server of this application is alive.

PingControllerITest.java

I followed Test Driven Development so first I created unit test class called PingControllerITest.java. I called this a ITest for integration test as we will be loading Spring Mock MVC engine to test our Rest API.

As general design, it is better to separate unit tests from integration tests. Unit tests should be able to run pretty quickly. I will show how to separate running unit tests from integration tests in a gradle project at a later blog.

I followed this blog to code this JUnit test as shown below.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PingControllerITest {
  @Autowired
  private MockMvc mockMvc;

  @Test
  public void testPingDefault() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/ping/").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().string(equalTo("Ping: Hi from SpringBoot")));
  }

  @Test
  public void testPingName() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/ping/Amar").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().string(equalTo("Ping: Hi Amar!, from SpringBoot, How are you?")));
  }
}

As shown in the code above, I used Hamcrest Matchers library to do the assertions. The following link shows the benefit of using Hamcrest instead of JUnit assertions.

There are two API I am testing above.

  1. /ping should return Ping: Hi from SpringBoot.
  2. /ping/amar should return Ping: Hi Amar!, from SpringBoot, How are you?

PingController.java

After failing PingControllerITest.java, I created class PingController.java to pass the tests. As shown in the code below, this Rest Controller is a basic Spring impmlementaion of REST.

@RestController
public class PingController {

  private static final String PING_MESSAGE = "Ping: Hi %s!, from SpringBoot, How are you?";
  private static final String PING_MESSAGE_DEFAULT = "Ping: Hi from SpringBoot";

  @RequestMapping({"/ping/{name}", "/ping"})
  public String ping(@PathVariable(required = false) Optional<String> name) {
    String pingMessage = PING_MESSAGE_DEFAULT;
    if (name.isPresent()) {
      pingMessage =  String.format(PING_MESSAGE, name.get());
    }
    return pingMessage;
  }
}

Now I can run the Spring boot application and test the Ping service using a browser.

The code for this blog is available at this link.

Leave a Reply

Your email address will not be published. Required fields are marked *