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.

I followed Test Driven Development so first I created unit test class called 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.

public class PingControllerITest {
  private MockMvc mockMvc;

  public void testPingDefault() throws Exception {
        .andExpect(content().string(equalTo("Ping: Hi from SpringBoot")));

  public void testPingName() throws Exception {
        .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?

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

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.

2 Replies to “Ping Service For Springboot Project”

Leave a Reply

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