Service Testing

Here, we are talking about testing our Microservice as a whole. For example, in the calculator service example we used throughout the chapter, we talked about making sure all the methods in the service are tested. Well, this is a very simple service, but in most cases, it would mean that all the layers (data, business, and so on) in a service work fine. A more real-world example would be that we are updating data for an employee and we hit a service with some data, which in turn calls a business validation layer to validate the correctness of the data. After validation, a data layer would be called and, finally, the data is stored. A service-level test would mean testing all these layers. We will discuss these layers in detail in the Levels of testing section.

Testing a Microservice from end to end can be complicated, as at times it might mean we need to bring up the service, make calls to the endpoint, and make sure things work fine. There are many tools available for our help. Here, I will use MockMVC, which integrates well with Spring Boot. This will demonstrate how we can test an end-to-end service. We will use the previous example for the calculator service, specifically the add operation, as follows:

@GetMapping("/add")
public int addNumber(int num1, int num2)
{
return(num1+num2);
}

Here is the code to test the preceding service:

//We will create a simple test to do end to end testing
package com.packt.Microservices.calculator2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@WebMvcTest(CalculatorController.class)
public class RestTest
{
@Autowired
private MockMvc mvc;
@Test
public void testRESTAdd()
throws Exception
{
mvc.perform( MockMvcRequestBuilders.get("/add? num1=1&num2=2")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content( ).string("3"));
}
}

The code that we are interested to test is the way we made a call to our add service. We make a mock call to the service and validated the end result, that is, we sent 1 and 2 as an input to the service and validated 3 as an output of the add operation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.212.160