Latest spring boot spring test unit test

Spring REST Integration Test – Mkyong.com

Spring Start Test

On this article we’ll present you the right 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.safety
    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 Hey 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.Record;
    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;

    @Before
    public void init ()
    E-book e-book = new e-book (1L, "Book Name", "Mkyong", new BigDecimal ("9.99"));
    when (mockRepository.findById (1 I)). thenReturn (Optionally available.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)));

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

    @Test
    public void find_allBook_OK () throws an exception

    Listing books = Arrays.asList (
    new guide (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);

    mockMvc.carry out (get ("/ books))
    .andExpect (content (). 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)));

    verify (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 new e-book = new guide (1L, "Spring Boot Guide", "mkyong", new BigDecimal ("2.99"));
    when (mockRepository.save (all (Guide.class))). thenReturn (newBook);

    mockMvc.carry out (publish ("/ 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 (Guide.class));

    @Test
    public void update_book_OK () throws an exception

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

    mockMvc.carry out (put ("/ books / 1")
    .content (om.writeValueAsString (updateBook))
    .header (HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
    .andExpect (content (). 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 (Guide.class))).
    String patchInJson = "" writer ":" Ultraman "";

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

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

    @Test
    public void patch_bookPrice_405 () throws an exception

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

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

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

    @Test
    public void delete_book_OK () throws an exception

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

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

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

    personal static blank printJSON (Object object)
    String outcome;
    attempt
    outcomes = om.writerWithDefaultPrettyPrinter (). writeValueAsString (objects);
    System.out.println (outcome);
    within the corridor (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.submit;
    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.standing;

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

    personal static remaining 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.carry out (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 (3))
    .andExpect (jsonPath ("$. errors", hasItem ("Author not allowed."))))
    .andExpect (jsonPath ("$. errors", hasItem ("Enter Author")))
    .andExpect (jsonPath ("$. errors", hasItem ("Enter Price")));

    examine (mockRepository, occasions (zero)). save (any (E-book.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.carry out (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 (E-book.class));

    1.3 Test @ WithMockUser for this spring's REST safety

    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.safety.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.Elective;

    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.outcome.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.carry out (get ("/ books / 1"))
    .andDo (print ())
    .andExpect (state (). isUnauthorized ());

    2. TestRestTemplate

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

    @Autowired
    personal TestRestTemplate restTemplate;

    2.1 CRUD check this spring on the REST Hey 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 rest
    @ActiveProfiles ("test")
    public class BookControllerRestTemplateTest

    personal static remaining ObjectMapper om = new ObjectMapper ();

    @Autowired
    personal TestRestTemplate restTemplate;

    @MockBean
    personal BookRepository mockRepository;

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

    @Test
    public void find_bookId_OK () Throw JSONException

    String expected = "id: 1, name:" Guide 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 (expected, reply.getBody (), false);

    verify (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 ebook (2L, "Book B", "Ah Dog", new BigDecimal ("2.99")));

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

    String Expected = om.writeValueAsString (books);

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

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

    examine (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 answer = 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

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

    String Anticipated = om.writeValueAsString (newBook);

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

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

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

    @Test
    public void update_book_OK () throws an exception

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

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

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

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

    examine (mockRepository, occasions (1)) findById (1L);
    verify (mockRepository, occasions (1)). save (any (E-book.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.change ("/ books / 1", HttpMethod.PUT, entity, String.class);

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

    verify (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 just isn’t allowed. "";

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

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

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

    assertEquals (HttpStatus.METHOD_NOT_ALLOWED, response.getStatusCode ());
    JSONAssert.assertEquals (anticipated, reply.getBody (), false);

    verify (mockRepository, occasions (1)) findById (1L);
    examine (mockRepository, occasions (zero)). save (any (Ebook.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 blank printJSON (Object object)
    String outcome;
    attempt
    results = om.writerWithDefaultPrettyPrinter (). writeValueAsString (objects);
    System.out.println (end result);
    in the corridor (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.verify;

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

    personal static last 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);

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

    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);

    examine (mockRepository, occasions (0)). save (any (E-book.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.change ("/ 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 (Ebook.class));

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

    2.3 Testing this Spring's REST Safety

    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.Elective;

    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 ultimate ObjectMapper om = new ObjectMapper ();

    // @ WithMockUser doesn’t work with TestRestTemplate
    @Autowired
    personal TestRestTemplate restTemplate;

    @MockBean
    personal BookRepository mockRepository;

    @Earlier than
    public void init ()
    Ebook = New E-book (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:" Guide to Bodhisattva's Way of life "by" Santideva ", Price: 15.41";

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

    printJSON (answer);

    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 (answer);

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

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

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

    Obtain Source

    References