Latest spring boot spring test unit test

Spring REST Integration Test – Mkyong.com

Spring Start Test

In this article we’ll show you the best way to check Spring Boot REST. Normally we use the MockMvc or TestRestTemplate check within the integration check

Methods used:

  • Spring Begin 2.1.2. ] pom.xml

    org.springframework.boot
    spring-boot-boot check
    check

    org.springframework.security
    spring security check
    check

    1. MockMvc

    @RunWith (SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class BookControllerTest

    @Autowired
    personal MockMvc mockMvc;

    1.1 CRUD Test for this Spring REST Hiya World Display

    package deal com.mkyong;

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.Ennen;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.manufacturing unit.annotation.Autowired;
    import org.springframework.boot.check.autoconfigure.net.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.check.context.SpringBootTest;
    import org.springframework.boot.check.mock.mockito.MockBean;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.check.context.ActiveProfiles;
    import org.springframework.check.context.junit4.SpringRunner;
    import org.springframework.check.net.servlet.MockMvc;

    import java.math.BigDecimal;
    import java.util.Arrays;
    import java.util.Listing;
    import java.util.Elective;

    import static org.hamcrest.Matchers.is;
    import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito. *;
    import static org.springframework.check.net.servlet.request.MockMvcRequestBuilders. *;
    import static org.springframework.check.net.servlet.end result.MockMvcResultMatchers. *;

    //@WebMvcTest(BookController.class)
    @RunWith (SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    @ActiveProfiles ("test")
    public class BookControllerTest

    personal static last ObjectMapper om = new ObjectMapper ();

    @Autowired
    personal MockMvc mockMvc;

    @MockBean
    personal BookRepository mockRepository;

    @Earlier than
    public void init ()
    Guide e-book = new guide (1L, "Book Name", "Mkyong", new BigDecimal ("9.99"));
    when (mockRepository.findById (1 I)). thenReturn (Non-compulsory.of (letter));

    @Test
    public void find_bookId_OK () throws an exception

    mockMvc.perform (get ("/ books / 1"))
    /*.andDo(print())*/
    .andExpect (content (). ContentType- (MediaType.APPLICATION_JSON_UTF8))
    .andExpect (state (). isOk ())
    .andExpect (jsonPath ("$. id" is (1)))
    .andExpect (jsonPath ("$. name" is "Book Name")))
    .andExpect (jsonPath ("$. author", on ("Mkyong")))
    .and ready (jsonPath ("$. price", is (9.99)));

    examine (mockRepository, occasions (1)) findById (1L);

    @Test
    public void find_allBook_OK () throws an exception

    Record books = Arrays.asList (
    new e-book (1L, "Book A", "Ah Pig", new BigDecimal ("1.99")),
    new guide (2L, "Book B", "Ah Dog", new BigDecimal ("2.99")));

    when (mockRepository.findAll ()). thenReturn (books);

    mockMvc.perform (get ("/ books))
    .andExpect (content material (). ContentType- (MediaType.APPLICATION_JSON_UTF8))
    .andExpect (state (). isOk ())
    .andExpect (jsonPath ("$", hasSize (2))
    .andExpect (jsonPath ("$ [0] .id", is (1)))
    .andExpect (jsonPath ("$ [0] .name" is ("Book A")))
    .andExpect (jsonPath ("$ [0] .author" is ("Ah Pig")))
    .andExpect (jsonPath ("$ [0] .price", on (1,99)))
    .andExpect (jsonPath ("$ [1] .id", is (2)))
    .andExpect (jsonPath ("$ [1] .name" is ("Book B")))
    .andExpect (jsonPath ("$ [1] .author" is ("Ah Dog")))
    and wait (jsonPath ("$ [1] .price", on (2.99)));

    examine (mockRepository, occasions (1)) findAll ();

    @Test
    public void find_bookIdNotFound_404 () throws an exception
    mockMvc.carry out (get ("/ books / 5")). andExpect (state (). isNotFound ());

    @Test
    public void save_book_OK () throws an exception

    E-book a brand new ebook = new ebook (1L, "Spring Boot Guide", "mkyong", new BigDecimal ("2.99"));
    when (mockRepository.save (all (E-book.class))). thenReturn (newBook);

    mockMvc.carry out (submit ("/ books")
    .content material (om.writeValueAsString (newBook))
    .header (HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
    /*.andDo(print())*/
    .andExpect (state (). isCreated ())
    .andExpect (jsonPath ("$. id" is (1)))
    .andExpect (jsonPath ("$. name" is "Spring Boot Guide")))
    .andExpect (jsonPath ("$. author", on ("mkyong")))
    and wait (jsonPath ("$. price", on (2.99)));

    verify (mockRepository, occasions (1)). save (any (E-book.class));

    @Test
    public void update_book_OK () throws an exception

    Guide updateBook = new e-book (1L, "ABC", "mkyong", new BigDecimal ("19.99"));
    when (mockRepository.save (all (Guide.class))). thenReturn (updateBook);

    mockMvc.perform (put ("/ books / 1")
    .content (om.writeValueAsString (updateBook))
    .header (HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
    .andExpect (content material (). ContentType- (MediaType.APPLICATION_JSON_UTF8))
    .andExpect (state (). isOk ())
    .andExpect (jsonPath ("$. id" is (1)))
    .andExpect (jsonPath ("$. name", on ("ABC")))
    .andExpect (jsonPath ("$. author", on ("mkyong")))
    .and wait (jsonPath ("$. price", on (19.99)));

    @Test
    public void patch_bookAuthor_OK () throws an exception

    when (mockRepository.save (any (E-book.class))).
    String patchInJson = "" writer ":" Ultraman "";

    mockMvc.carry out (patch ("/ books / 1")
    .content (patchInJson)
    .header (HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
    .andExpect (content (). ContentType- (MediaType.APPLICATION_JSON_UTF8))
    .andExpect (state (). isOk ());

    examine (mockRepository, occasions (1)) findById (1L);
    examine (mockRepository, occasions (1)). save (any (Ebook.class));

    @Test
    public void patch_bookPrice_405 () throws an exception

    String patchInJson = "" worth ":" 99.99 "";

    mockMvc.carry out (patch ("/ books / 1")
    .content material (patchInJson)
    .header (HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
    .andExpect (state (). isMethodNotAllowed ());

    verify (mockRepository, occasions (1)) findById (1L);
    verify (mockRepository, occasions (zero)). save (any (Ebook.class));

    @Test
    public void delete_book_OK () throws an exception

    donothing (). when (mockRepository) .deleteById (1 I);

    mockMvc.carry out (remove ("/ books / 1"))
    /*.andDo(print())*/
    .andExpect (state (). isOk ());

    examine (mockRepository, occasions (1)) deleteById (1L);

    personal static blank printJSON (Object object)
    String end result;
    attempt
    results = om.writerWithDefaultPrettyPrinter (). writeValueAsString (objects);
    System.out.println (outcome);
    within the hall (JsonProcessingException e)
    e.printStackTrace ();

    1.2 Testing this spring's REST validation

    package deal com.mkyong;

    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.manufacturing unit.annotation.Autowired;
    import org.springframework.boot.check.autoconfigure.net.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.check.context.SpringBootTest;
    import org.springframework.boot.check.mock.mockito.MockBean;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.check.context.ActiveProfiles;
    import org.springframework.check.context.junit4.SpringRunner;
    import org.springframework.check.net.servlet.MockMvc;

    import static org.hamcrest.Matchers. *;
    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito.occasions;
    import static org.mockito.Mockito.confirm;
    import static org.springframework.check.net.servlet.request.MockMvcRequestBuilders.publish;
    import static org.springframework.check.net.servlet.end result.MockMvcResultHandlers.print;
    import static org.springframework.check.net.servlet.outcome.MockMvcResultMatchers.jsonPath;
    import static org.springframework.check.net.servlet.end result.MockMvcResultMatchers.status;

    @RunWith (SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    @ActiveProfiles ("test")
    public class BookControllerTest

    personal static ultimate ObjectMapper om = new ObjectMapper ();

    @Autowired
    personal MockMvc mockMvc;

    @MockBean
    personal BookRepository mockRepository;

    / *

    "Time stamp": "2019-03-05T09: 34: 13,280 + 0000"
    "Status": 400,
    "Errors": [“Author is not allowed.”,”Please provide a price”,”Please provide a author”]

    * /
    @Test
    public void save_emptyAuthor_emptyPrice_400 () throws an exception

    The string bookInJson = "" identify ":" ABC "";

    mockMvc.perform (publish ("/ books")
    .content (bookInJson)
    .header (HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
    .andDo (print ())
    .andExpect (state (). isBadRequest ())
    .andExpect (jsonPath ("$. timestamp" is (notNullValue ())))
    .and ready (jsonPath ("$. status" is (400)))
    .andExpect (jsonPath ("$. errors). isArray ())
    .andExpect (jsonPath ("$. errors", hasSize (three))
    .andExpect (jsonPath ("$. errors", hasItem ("Author not allowed."))))
    .andExpect (jsonPath ("$. errors", hasItem ("Enter Author")))
    .andExpect (jsonPath ("$. errors", hasItem ("Enter Price")));

    verify (mockRepository, occasions (0)). save (any (Ebook.class));

    / *

    "Time Stamp": "2019-03-05T09: 34: 13,207 + 0000"
    "Status": 400,
    "Errors": [“Author is not allowed.”]

    * /
    @Test
    public void save_invalidAuthor_400 () throws an exception

    String bookInJson = "" identify ":" Spring REST tutorials "," writer ":" abc "," worth ":" 9.99 "";

    mockMvc.perform (publish ("/ books")
    .content material (bookInJson)
    .header (HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
    .andDo (print ())
    .andExpect (state (). isBadRequest ())
    .andExpect (jsonPath ("$. timestamp" is (notNullValue ())))
    .and waiting (jsonPath ("$. status" is (400)))
    .andExpect (jsonPath ("$. errors). isArray ())
    .andExpect (jsonPath ("$. errors", hasSize (1))
    .andExpect (jsonPath ("$. errors", hasItem ("Author not allowed.")));

    examine (mockRepository, occasions (zero)). save (any (Ebook.class));

    1.three Test @ WithMockUser for this spring's REST security

    package deal com.mkyong;

    import org.junit.Ennen;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.manufacturing unit.annotation.Autowired;
    import org.springframework.boot.check.autoconfigure.net.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.check.context.SpringBootTest;
    import org.springframework.boot.check.mock.mockito.MockBean;
    import org.springframework.security.check.context.help.WithMockUser;
    import org.springframework.check.context.ActiveProfiles;
    import org.springframework.check.context.junit4.SpringRunner;
    import org.springframework.check.net.servlet.MockMvc;

    import java.math.BigDecimal;
    import java.util.Optionally available;

    import static org.hamcrest.Matchers.is;
    import static org.mockito.Mockito.when;
    import static org.springframework.check.net.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.check.net.servlet.outcome.MockMvcResultHandlers.print;
    import static org.springframework.check.net.servlet.outcome.MockMvcResultMatchers.jsonPath;
    import static org.springframework.check.net.servlet.end result.MockMvcResultMatchers.status;

    @RunWith (SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    @ActiveProfiles ("test")
    public class BookControllerTest

    @Autowired
    personal MockMvc mockMvc;

    @MockBean
    personal BookRepository mockRepository;

    @Before
    public void init ()
    E-book = New Ebook (1L, "Guide to Bodhisattva's Lifestyle", "Santideva", New BigDecimal ("15.41"));
    when (mockRepository.findById (1 I)). thenReturn (Optionally available.of (letter));

    // @ WithMockUser (username = "USER")
    @WithMockUser ("USER")
    @Test
    public void find_login_ok () throws an exception

    mockMvc.carry out (get ("/ books / 1"))
    .andDo (print ())
    .andExpect (state (). isOk ())
    .andExpect (jsonPath ("$. id" is (1)))
    .andExpect (jsonPath ("$. name" is a "Guide to Bodhisattva's Lifestyle")))
    .andExpect (jsonPath ("$. author", on ("Santideva")))
    and wait (jsonPath ("$. price", is (15,41)));

    @Test
    public void find_nologin_401 () throws an exception
    mockMvc.perform (get ("/ books / 1"))
    .andDo (print ())
    .andExpect (state (). isUnauthorized ());

    2. TestRestTemplate

    @RunWith (SpringRunner.class)
    @SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // for rest
    @ActiveProfiles ("test")
    public class BookControllerRestTemplateTest

    @Autowired
    personal TestRestTemplate restTemplate;

    2.1 CRUD check this spring on the REST Good day World display

    package deal com.mkyong;

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    deliver org.json.JSONException;
    import org.junit.Ennen;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.skyscreamer.jsonassert.JSONAssert;
    import org.springframework.beans.manufacturing unit.annotation.Autowired;
    import org.springframework.boot.check.context.SpringBootTest;
    import org.springframework.boot.check.mock.mockito.MockBean;
    import org.springframework.boot.check.net.shopper.TestRestTemplate;
    import org.springframework.http. *;
    import org.springframework.check.context.ActiveProfiles;
    import org.springframework.check.context.junit4.SpringRunner;

    import java.math.BigDecimal;
    import java.util.Arrays;
    import java.util.Listing;
    import java.util.Optionally available;

    import static org.junit.Assert.assertEquals;
    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito. *;

    @RunWith (SpringRunner.class)
    @SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // for relaxation
    @ActiveProfiles ("test")
    public class BookControllerRestTemplateTest

    personal static remaining ObjectMapper om = new ObjectMapper ();

    @Autowired
    personal TestRestTemplate restTemplate;

    @MockBean
    personal BookRepository mockRepository;

    @Earlier than
    public void init ()
    E-book guide = new guide (1L, "Book Name", "Mkyong", new BigDecimal ("9.99"));
    when (mockRepository.findById (1 I)). thenReturn (Optionally available.of (letter));

    @Test
    public void find_bookId_OK () Throw JSONException

    String anticipated = "id: 1, name:" Ebook title "by" Mkyong ", price: 9.99";

    ResponseEntity reply = restTemplate.getForEntity ("/ books / 1", character course);

    assertEquals (HttpStatus.OK, response.getStatusCode ());
    assertEquals (MediaType.APPLICATION_JSON_UTF8, response.getHeaders (). getContentType ());

    JSONAssert.assertEquals (anticipated, reply.getBody (), false);

    verify (mockRepository, occasions (1)) findById (1L);

    @Test
    public void find_allBook_OK () throws an exception

    Record books = Arrays.asList (
    new ebook (1L, "Book A", "Ah Pig", new BigDecimal ("1.99")),
    new e-book (2L, "Book B", "Ah Dog", new BigDecimal ("2.99")));

    when (mockRepository.findAll ()). thenReturn (books);

    String Anticipated = om.writeValueAsString (books);

    ResponseEntity reply = restTemplate.getForEntity ("/ books", String.class);

    assertEquals (HttpStatus.OK, response.getStatusCode ());
    JSONAssert.assertEquals (expected, answer.getBody (), false);

    verify (mockRepository, occasions (1)) findAll ();

    @Test
    public void find_bookIdNotFound_404 () throws an exception

    String expected = "status: 404, error: Not found", message: "Book ID not found: 5", path: "/ books / 5" ";

    ResponseEntity reply = restTemplate.getForEntity ("/ books / 5", character course);

    assertEquals (HttpStatus.NOT_FOUND, response.getStatusCode ());
    JSONAssert.assertEquals (expected, answer.getBody (), false);

    @Test
    public void save_book_OK () throws an exception

    Guide a new ebook = new guide (1L, "Spring Boot Guide", "mkyong", new BigDecimal ("2.99"));
    when (mockRepository.save (all (E-book.class))). thenReturn (newBook);

    String Anticipated = om.writeValueAsString (newBook);

    ResponseEntity answer = restTemplate.postForEntity ("/ books", NewBook, String.class);

    assertEquals (HttpStatus.CREATED, response.getStatusCode ());
    JSONAssert.assertEquals (expected, reply.getBody (), false);

    examine (mockRepository, occasions (1)). save (any (Guide.class));

    @Test
    public void update_book_OK () throws an exception

    Guide updateBook = new guide (1L, "ABC", "mkyong", new BigDecimal ("19.99"));
    when (mockRepository.save (all (E-book.class))). thenReturn (updateBook);

    HttpHeaders headers = new HttpHeaders ();
    headers.setContentType (MediaType.APPLICATION_JSON);
    HttpEntity entity = new HttpEntity <> (om.writeValueAsString (replace ebook), headers);

    ResponseEntity answer = restTemplate.change ("/ books / 1", HttpMethod.PUT, entity, String.class);

    assertEquals (HttpStatus.OK, response.getStatusCode ());
    JSONAssert.assertEquals (om.writeValueAsString (updateBook), answer.getBody (), false);

    verify (mockRepository, occasions (1)) findById (1L);
    verify (mockRepository, occasions (1)). save (any (Ebook.class));

    @Test
    public void patch_bookAuthor_OK ()

    when (mockRepository.save (any (E-book.class))).
    String patchInJson = "" writer ":" Ultraman "";

    HttpHeaders headers = new HttpHeaders ();
    headers.setContentType (MediaType.APPLICATION_JSON);
    HttpEntity entity = new HttpEntity <> (patchInJson, headlines);

    ResponseEntity reply = restTemplate.trade ("/ books / 1", HttpMethod.PUT, entity, String.class);

    assertEquals (HttpStatus.OK, response.getStatusCode ());

    examine (mockRepository, occasions (1)) findById (1L);
    examine (mockRepository, occasions (1)). save (any (E-book.class));

    @Test
    public void patch_bookPrice_405 () throws JSONException

    String anticipated = "status: 405, error:" technique not allowed ", message:" Area [price] update is just not allowed. "";

    String patchInJson = "" worth ":" 99.99 "";

    HttpHeaders headers = new HttpHeaders ();
    headers.setContentType (MediaType.APPLICATION_JSON);
    HttpEntity entity = new HttpEntity <> (patchInJson, headlines);

    ResponseEntity answer = restTemplate.trade ("/ books / 1", HttpMethod.PATCH, entity, String.class);

    assertEquals (HttpStatus.METHOD_NOT_ALLOWED, response.getStatusCode ());
    JSONAssert.assertEquals (expected, answer.getBody (), false);

    verify (mockRepository, occasions (1)) findById (1L);
    verify (mockRepository, occasions (0)). save (any (E-book.class));

    @Test
    public void delete_book_OK ()

    donothing (). when (mockRepository) .deleteById (1 I);

    HttpEntity entity = new HttpEntity <> (zero, new HttpHeaders ());
    ResponseEntity reply = restTemplate.change ("/ books / 1", HttpMethod.DELETE, entity, String.class);

    assertEquals (HttpStatus.OK, response.getStatusCode ());

    examine (mockRepository, occasions (1)) deleteById (1L);

    personal static clean printJSON (Object object)
    String outcome;
    attempt
    outcomes = om.writerWithDefaultPrettyPrinter (). writeValueAsString (objects);
    System.out.println (outcome);
    within the hall (JsonProcessingException e)
    e.printStackTrace ();

    2.2 Testing this Spring REST Validation

    package deal com.mkyong;

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    deliver org.json.JSONException;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.skyscreamer.jsonassert.JSONAssert;
    import org.springframework.beans.manufacturing unit.annotation.Autowired;
    import org.springframework.boot.check.context.SpringBootTest;
    import org.springframework.boot.check.mock.mockito.MockBean;
    import org.springframework.boot.check.net.shopper.TestRestTemplate;
    import org.springframework.http. *;
    import org.springframework.check.context.ActiveProfiles;
    import org.springframework.check.context.junit4.SpringRunner;

    import static org.junit.Assert.assertEquals;
    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito.occasions;
    import static org.mockito.Mockito.confirm;

    @RunWith (SpringRunner.class)
    @SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // for rest
    @ActiveProfiles ("test")
    public class BookControllerRestTemplateTest

    personal static ultimate ObjectMapper om = new ObjectMapper ();

    @Autowired
    personal TestRestTemplate restTemplate;

    @MockBean
    personal BookRepository mockRepository;

    / *

    "Time stamp": "2019-03-05T09: 34: 13,280 + 0000"
    "Status": 400,
    "Errors": [“Author is not allowed.”,”Please provide a price”,”Please provide a author”]

    * /
    @Test
    public void save_emptyAuthor_emptyPrice_400 () throws JSONException

    The string bookInJson = "" identify ":" ABC "";

    HttpHeaders headers = new HttpHeaders ();
    headers.setContentType (MediaType.APPLICATION_JSON);
    HttpEntity entity = new HttpEntity <> (bookInJson, headlines);

    // send json with POST
    ResponseEntity answer = restTemplate.postForEntity ("/ books", entity, String.class);
    // printJSON (answer);

    String ExpectedJson = "" Status ": 400," Errors ": [“Author is not allowed.”,”Please provide a price”,”Please provide a author”]";
    assertEquals (HttpStatus.BAD_REQUEST, response.getStatusCode ());
    JSONAssert.assertEquals (expectedJson, response.getBody (), false);

    verify (mockRepository, occasions (zero)). save (any (Ebook.class));

    / *

    "Time Stamp": "2019-03-05T09: 34: 13,207 + 0000"
    "Status": 400,
    "Errors": [“Author is not allowed.”]

    * /
    @Test
    public void save_invalidAuthor_400 () throws JSONException

    String bookInJson = "" identify ":" Spring REST tutorials "," writer ":" abc "," worth ":" 9.99 "";

    HttpHeaders headers = new HttpHeaders ();
    headers.setContentType (MediaType.APPLICATION_JSON);
    HttpEntity entity = new HttpEntity <> (bookInJson, headlines);

    // Attempt switching
    ResponseEntity answer = restTemplate.trade ("/ books", HttpMethod.POST, entity, String.class);

    The string expectedJson = "" standing ": 400," errors ": [“Author is not allowed.”]";
    assertEquals (HttpStatus.BAD_REQUEST, response.getStatusCode ());
    JSONAssert.assertEquals (expectedJson, response.getBody (), false);

    examine (mockRepository, occasions (zero)). save (any (E-book.class));

    personal static clean printJSON (Object object)
    String end result;
    attempt
    results = om.writerWithDefaultPrettyPrinter (). writeValueAsString (objects);
    System.out.println (outcome);
    within the corridor (JsonProcessingException e)
    e.printStackTrace ();

    2.3 Testing this Spring's REST Protection

    package deal com.mkyong;

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.Ennen;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.skyscreamer.jsonassert.JSONAssert;
    import org.springframework.beans.manufacturing unit.annotation.Autowired;
    import org.springframework.boot.check.context.SpringBootTest;
    import org.springframework.boot.check.mock.mockito.MockBean;
    import org.springframework.boot.check.net.shopper.TestRestTemplate;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.check.context.ActiveProfiles;
    import org.springframework.check.context.junit4.SpringRunner;

    import java.math.BigDecimal;
    import java.util.Non-compulsory;

    import static org.junit.Assert.assertEquals;
    import static org.mockito.Mockito.when;

    @RunWith (SpringRunner.class)
    @SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    @ActiveProfiles ("test")
    public class BookControllerRestTemplateTest

    personal static remaining ObjectMapper om = new ObjectMapper ();

    // @ WithMockUser does not work with TestRestTemplate
    @Autowired
    personal TestRestTemplate restTemplate;

    @MockBean
    personal BookRepository mockRepository;

    @Earlier than
    public void init ()
    Ebook = New Ebook (1L, "Guide to Bodhisattva's Lifestyle", "Santideva", New BigDecimal ("15.41"));
    when (mockRepository.findById (1 I)). thenReturn (Elective.of (letter));

    @Test
    public void find_login_ok () throws an exception

    String anticipated = "id: 1, title:" Information to Bodhisattva's Way of life "by" Santideva ", Price: 15.41";

    ResponseEntity answer = restTemplate
    .withBasicAuth ("user", "password")
    .getForEntity ("/ books / 1", String.class);

    printJSON (reply);

    assertEquals (MediaType.APPLICATION_JSON_UTF8, response.getHeaders (). getContentType ());
    assertEquals (HttpStatus.OK, response.getStatusCode ());

    JSONAssert.assertEquals (anticipated, answer.getBody (), false);

    @Test
    public void find_nologin_401 () throws an exception

    String Anticipated = "" Status ": 401," Error ":" Unauthorized "," Message ":" Unauthorized "," Path ":" / books / 1 "";

    ResponseEntity answer = restTemplate
    .getForEntity ("/ books / 1", String.class);

    printJSON (reply);

    assertEquals (MediaType.APPLICATION_JSON_UTF8, response.getHeaders (). getContentType ());
    assertEquals (HttpStatus.UNAUTHORIZED, response.getStatusCode ());

    JSONAssert.assertEquals (expected, reply.getBody (), false);

    personal static clean printJSON (Object object)
    String end result;
    attempt
    outcomes = om.writerWithDefaultPrettyPrinter (). writeValueAsString (objects);
    System.out.println (end result);
    in the corridor (JsonProcessingException e)
    e.printStackTrace ();

    Obtain Source

    References