Rozruch sprężynowy - test jednostki kontrolera odpoczynku
Spring Boot zapewnia łatwy sposób na napisanie testu jednostkowego dla pliku kontrolera odpoczynku. Z pomocą SpringJUnit4ClassRunner i MockMvc możemy stworzyć kontekst aplikacji internetowej do zapisu pliku Unit Test for Rest Controller.
Testy jednostkowe powinny być napisane pod src/test/java Zasoby katalogu i ścieżki klas do napisania testu powinny być umieszczone w katalogu src/test/resources informator.
Aby napisać test jednostkowy, musimy dodać zależność Spring Boot Starter Test w pliku konfiguracyjnym kompilacji, jak pokazano poniżej.
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency> 
    Użytkownicy Gradle mogą dodać następującą zależność w pliku build.gradle.
testCompile('org.springframework.boot:spring-boot-starter-test') 
    Przed napisaniem przypadku testowego powinniśmy najpierw zbudować usługi sieciowe RESTful. Więcej informacji na temat tworzenia usług internetowych zgodnych ze standardem REST można znaleźć w rozdziale poświęconym temu samemu podanemu w tym samouczku.
Pisanie testu jednostkowego dla kontrolera REST
W tej sekcji zobaczmy, jak napisać test jednostkowy dla kontrolera REST.
Najpierw musimy utworzyć plik klasy abstrakcyjnej używany do tworzenia kontekstu aplikacji internetowej za pomocą MockMvc i zdefiniować metody mapToJson () i mapFromJson (), aby przekonwertować obiekt Java na ciąg JSON i przekonwertować ciąg JSON na obiekt Java.
package com.tutorialspoint.demo;
import java.io.IOException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
@WebAppConfiguration
public abstract class AbstractTest {
   protected MockMvc mvc;
   @Autowired
   WebApplicationContext webApplicationContext;
   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {
      
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
} 
    Następnie napisz plik klasy, który rozszerza klasę AbstractTest i napisz Test jednostkowy dla każdej metody, takiej jak GET, POST, PUT i DELETE.
Kod przypadku testowego GET API znajduje się poniżej. Ten interfejs API służy do przeglądania listy produktów.
@Test
public void getProductsList() throws Exception {
   String uri = "/products";
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
      .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();
   
   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   Product[] productlist = super.mapFromJson(content, Product[].class);
   assertTrue(productlist.length > 0);
} 
    Kod przypadku testowego POST API jest podany poniżej. To API służy do tworzenia produktu.
@Test
public void createProduct() throws Exception {
   String uri = "/products";
   Product product = new Product();
   product.setId("3");
   product.setName("Ginger");
   
   String inputJson = super.mapToJson(product);
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
      .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();
   
   int status = mvcResult.getResponse().getStatus();
   assertEquals(201, status);
   String content = mvcResult.getResponse().getContentAsString();
   assertEquals(content, "Product is created successfully");
} 
    Kod przypadku testowego PUT API znajduje się poniżej. Ten interfejs API służy do aktualizacji istniejącego produktu.
@Test
public void updateProduct() throws Exception {
   String uri = "/products/2";
   Product product = new Product();
   product.setName("Lemon");
   
   String inputJson = super.mapToJson(product);
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)
      .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();
   
   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   assertEquals(content, "Product is updated successsfully");
} 
    Kod dla Usuń przypadek testowy API znajduje się poniżej. Ten interfejs API usunie istniejący produkt.
@Test
public void deleteProduct() throws Exception {
   String uri = "/products/2";
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();
   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   assertEquals(content, "Product is deleted successsfully");
} 
    Pełny plik klasy testu kontrolera znajduje się poniżej -
package com.tutorialspoint.demo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.tutorialspoint.demo.model.Product;
public class ProductServiceControllerTest extends AbstractTest {
   @Override
   @Before
   public void setUp() {
      super.setUp();
   }
   @Test
   public void getProductsList() throws Exception {
      String uri = "/products";
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
         .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();
      
      int status = mvcResult.getResponse().getStatus();
      assertEquals(200, status);
      String content = mvcResult.getResponse().getContentAsString();
      Product[] productlist = super.mapFromJson(content, Product[].class);
      assertTrue(productlist.length > 0);
   }
   @Test
   public void createProduct() throws Exception {
      String uri = "/products";
      Product product = new Product();
      product.setId("3");
      product.setName("Ginger");
      String inputJson = super.mapToJson(product);
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
         .contentType(MediaType.APPLICATION_JSON_VALUE)
         .content(inputJson)).andReturn();
      
      int status = mvcResult.getResponse().getStatus();
      assertEquals(201, status);
      String content = mvcResult.getResponse().getContentAsString();
      assertEquals(content, "Product is created successfully");
   }
   @Test
   public void updateProduct() throws Exception {
      String uri = "/products/2";
      Product product = new Product();
      product.setName("Lemon");
      String inputJson = super.mapToJson(product);
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)
         .contentType(MediaType.APPLICATION_JSON_VALUE)
         .content(inputJson)).andReturn();
      
      int status = mvcResult.getResponse().getStatus();
      assertEquals(200, status);
      String content = mvcResult.getResponse().getContentAsString();
      assertEquals(content, "Product is updated successsfully");
   }
   @Test
   public void deleteProduct() throws Exception {
      String uri = "/products/2";
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();
      int status = mvcResult.getResponse().getStatus();
      assertEquals(200, status);
      String content = mvcResult.getResponse().getContentAsString();
      assertEquals(content, "Product is deleted successsfully");
   }
} 
    Możesz utworzyć wykonywalny plik JAR i uruchomić aplikację Spring Boot za pomocą poleceń Maven lub Gradle podanych poniżej -
W przypadku Mavena możesz użyć polecenia podanego poniżej -
mvn clean install 
    Teraz możesz zobaczyć wyniki testu w oknie konsoli.
                W przypadku Gradle możesz użyć polecenia, jak pokazano poniżej -
gradle clean build 
    Możesz zobaczyć pozostałe wyniki w oknie konsoli, jak pokazano poniżej.