JAVA-3520: Moved spring-mvc-basics-3 inside spring-web-modules

This commit is contained in:
sampadawagde
2020-12-23 18:51:25 +05:30
parent fe6e6e1637
commit 6507954fe3
78 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,13 @@
package com.baeldung;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.baeldung.spring.Application;
@SpringBootTest(classes = Application.class)
public class AppContextIntegrationTest {
@Test
public void contextLoads() {
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.Modes;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class SpringBootApplicationIntegrationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(4)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id", equalTo(1)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.id", equalTo(1)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id", equalTo(1)));
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
import org.junit.Test;
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.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}

View File

@@ -0,0 +1,80 @@
package com.baeldung;
import com.baeldung.boot.Application;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootMailIntegrationTest {
@Autowired
private JavaMailSender javaMailSender;
private Wiser wiser;
private String userTo = "user2@localhost";
private String userFrom = "user1@localhost";
private String subject = "Test subject";
private String textMail = "Text subject mail";
@Before
public void setUp() throws Exception {
final int TEST_PORT = 8025;
wiser = new Wiser(TEST_PORT);
wiser.start();
}
@After
public void tearDown() throws Exception {
wiser.stop();
}
@Test
public void givenMail_whenSendAndReceived_thenCorrect() throws Exception {
SimpleMailMessage message = composeEmailMessage();
javaMailSender.send(message);
List<WiserMessage> messages = wiser.getMessages();
assertThat(messages, hasSize(1));
WiserMessage wiserMessage = messages.get(0);
assertEquals(userFrom, wiserMessage.getEnvelopeSender());
assertEquals(userTo, wiserMessage.getEnvelopeReceiver());
assertEquals(subject, getSubject(wiserMessage));
assertEquals(textMail, getMessage(wiserMessage));
}
private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException {
return wiserMessage.getMimeMessage().getContent().toString().trim();
}
private String getSubject(WiserMessage wiserMessage) throws MessagingException {
return wiserMessage.getMimeMessage().getSubject();
}
private SimpleMailMessage composeEmailMessage() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(userTo);
mailMessage.setReplyTo(userFrom);
mailMessage.setFrom(userFrom);
mailMessage.setSubject(subject);
mailMessage.setText(textMail);
return mailMessage;
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.cachedrequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.util.StreamUtils;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class CachedBodyHttpServletRequestUnitTest extends TestCase {
private CachedBodyServletInputStream servletInputStream;
@After
public void cleanUp() throws IOException {
if (null != servletInputStream) {
servletInputStream.close();
}
}
@Test
public void testGivenHttpServletRequestWithBody_whenCalledGetInputStream_ThenGetsServletInputStreamWithSameBody() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
MockHttpServletRequest mockeddHttpServletRequest = new MockHttpServletRequest();
mockeddHttpServletRequest.setContent(cachedBody);
CachedBodyHttpServletRequest request = new CachedBodyHttpServletRequest(mockeddHttpServletRequest);
// when
InputStream inputStream = request.getInputStream();
// then
assertEquals(new String(cachedBody), new String(StreamUtils.copyToByteArray(inputStream)));
}
@Test
public void testGivenHttpServletRequestWithBody_whenCalledGetReader_ThenGetBufferedReaderWithSameBody() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
MockHttpServletRequest mockeddHttpServletRequest = new MockHttpServletRequest();
mockeddHttpServletRequest.setContent(cachedBody);
CachedBodyHttpServletRequest request = new CachedBodyHttpServletRequest(mockeddHttpServletRequest);
// when
BufferedReader bufferedReader = request.getReader();
// then
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
assertEquals(new String(cachedBody), builder.toString());
}
}

View File

@@ -0,0 +1,98 @@
package com.baeldung.cachedrequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ReadListener;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.util.StreamUtils;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class CachedBodyServletInputStreamUnitTest extends TestCase {
private CachedBodyServletInputStream servletInputStream;
@After
public void cleanUp() throws IOException {
if (null != servletInputStream) {
servletInputStream.close();
}
}
@Test
public void testGivenServletInputStreamCreated_whenCalledisFinished_Thenfalse() {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
boolean finished = servletInputStream.isFinished();
// then
assertFalse(finished);
}
@Test
public void testGivenServletInputStreamCreatedAndBodyRead_whenCalledisFinished_ThenTrue() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
StreamUtils.copyToByteArray(servletInputStream);
// when
boolean finished = servletInputStream.isFinished();
// then
assertTrue(finished);
}
@Test
public void testGivenServletInputStreamCreatedAndBodyRead_whenCalledIsReady_ThenTrue() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
boolean ready = servletInputStream.isReady();
// then
assertTrue(ready);
}
@Test
public void testGivenServletInputStreamCreated_whenCalledIsRead_ThenReturnsBody() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = servletInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
// then
assertEquals(new String(cachedBody), new String(byteArrayOutputStream.toByteArray()));
}
@Test(expected = UnsupportedOperationException.class)
public void testGivenServletInputStreamCreated_whenCalledIsRead_ThenThrowsException() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
servletInputStream.setReadListener(Mockito.mock(ReadListener.class));
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.cachedrequest;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class ContentCachingFilterUnitTest extends TestCase {
@InjectMocks
private ContentCachingFilter filterToTest;
@Test
public void testGivenHttpRequest_WhenDoFilter_thenCreatesRequestWrapperObject() throws IOException, ServletException {
// Given
MockHttpServletRequest mockedRequest = new MockHttpServletRequest();
MockHttpServletResponse mockedResponse = new MockHttpServletResponse();
FilterChain mockedFilterChain = Mockito.mock(FilterChain.class);
// when
filterToTest.doFilter(mockedRequest, mockedResponse, mockedFilterChain);
// then
Mockito.verify(mockedFilterChain, Mockito.times(1))
.doFilter(Mockito.any(CachedBodyHttpServletRequest.class), Mockito.any(MockHttpServletResponse.class));
}
}

View File

@@ -0,0 +1,64 @@
package com.baeldung.cachedrequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.io.IOException;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { HttpRequestDemoConfig.class, ContentCachingFilter.class, PrintRequestContentFilter.class, PersonController.class })
@WebAppConfiguration
public class PersonControllerIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
ObjectMapper objectMapper = new ObjectMapper();
@Autowired
private ContentCachingFilter contentCachingFilter;
@Autowired
private PrintRequestContentFilter printRequestContentFilter;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.addFilter(contentCachingFilter, "/**")
.addFilter(printRequestContentFilter, "/**")
.build();
}
@Test
public void whenValidInput_thenCreateBook() throws IOException, Exception {
// assign - given
Person person = new Person("sumit", "abc", 100);
// act - when
ResultActions result = mockMvc.perform(post("/person").accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(person)));
// assert - then
result.andExpect(status().isNoContent());
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.cachedrequest;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class PrintRequestContentFilterUnitTest extends TestCase {
@InjectMocks
private PrintRequestContentFilter filterToTest;
@Test
public void testGivenHttpRequest_WhenDoFilter_thenReadsBody() throws IOException, ServletException {
// Given
MockHttpServletRequest mockedRequest = new MockHttpServletRequest();
MockHttpServletResponse mockedResponse = new MockHttpServletResponse();
FilterChain mockedFilterChain = Mockito.mock(FilterChain.class);
CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(mockedRequest);
// when
filterToTest.doFilter(cachedBodyHttpServletRequest, mockedResponse, mockedFilterChain);
// then
Mockito.verify(mockedFilterChain, Mockito.times(1))
.doFilter(cachedBodyHttpServletRequest, mockedResponse);
}
}

View File

@@ -0,0 +1,86 @@
package com.baeldung.headers.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.baeldung.spring.headers.controller.ReadHeaderRestController;
@SpringJUnitWebConfig(ReadHeaderRestControllerIntegrationTest.Config.class)
@ExtendWith(SpringExtension.class)
public class ReadHeaderRestControllerIntegrationTest {
private static final Log LOG = LogFactory.getLog(ReadHeaderRestControllerIntegrationTest.class);
@Configuration
static class Config {
}
private MockMvc mockMvc;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new ReadHeaderRestController())
.build();
}
@Test
public void whenGetRequestSentToAllHeaders_thenStatusOkAndTextReturned() throws Exception {
mockMvc.perform(get("/listHeaders").header("my-header", "Test"))
.andExpect(status().isOk())
.andExpect(content().string("Listed 1 headers"));
}
@Test
public void whenGetRequestSentToMultiValue_thenStatusOkAndTextReturned() throws Exception {
mockMvc.perform(get("/multiValue").header("my-header", "ABC", "DEF", "GHI"))
.andExpect(status().isOk())
.andExpect(content().string("Listed 1 headers"));
}
@Test
public void whenGetRequestSentToGreeting_thenStatusOKAndGreetingReturned() throws Exception {
mockMvc.perform(get("/greeting").header("accept-language", "de"))
.andExpect(status().isOk())
.andExpect(content().string("Hallo!"));
}
@Test
public void whenGetRequestSentToDouble_thenStatusOKAndCorrectResultReturned() throws Exception {
mockMvc.perform(get("/double").header("my-number", 2))
.andExpect(status().isOk())
.andExpect(content().string("2 * 2 = 4"));
}
@Test
public void whenGetRequestSentToGetBaseUrl_thenStatusOkAndHostReturned() throws Exception {
mockMvc.perform(get("/getBaseUrl").header("host", "localhost:8080"))
.andExpect(status().isOk())
.andExpect(content().string("Base URL = http://localhost:8080"));
}
@Test
public void whenGetRequestSentToNonRequiredHeaderWithoutHeader_thenStatusOKAndMessageReturned() throws Exception {
mockMvc.perform(get("/nonRequiredHeader"))
.andExpect(status().isOk())
.andExpect(content().string("Was the optional header present? No!"));
}
@Test
public void whenGetRequestSentToDefaultWithoutHeader_thenStatusOKAndMessageReturned() throws Exception {
mockMvc.perform(get("/default"))
.andExpect(status().isOk())
.andExpect(content().string("Optional Header is 3600"));
}
}

View File

@@ -0,0 +1,87 @@
package com.baeldung.spring.slash;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.net.URI;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class SlashParsingControllerIntTest {
@Autowired
private MockMvc mockMvc;
@Test
public void whenUsingPathVariablemWithoutSlashes_thenStatusOk() throws Exception {
final String stringWithoutSlashes = "noslash";
MvcResult mvcResult = mockMvc.perform(get("/slash/mypaths/" + stringWithoutSlashes))
.andExpect(status().isOk())
.andReturn();
assertEquals(stringWithoutSlashes, mvcResult.getResponse()
.getContentAsString());
}
@Test
public void whenUsingPathVariableWithSlashes_thenStatusNotFound() throws Exception {
final String stringWithSlashes = "url/with/slashes";
mockMvc.perform(get("/slash/mypaths/" + stringWithSlashes))
.andExpect(status().isNotFound());
}
@Test
public void givenAllFallbackEndpoint_whenUsingPathWithSlashes_thenStatusOk() throws Exception {
final String stringWithSlashes = "url/for/testing/purposes";
MvcResult mvcResult = mockMvc.perform(get("/slash/all/" + stringWithSlashes))
.andExpect(status().isOk())
.andReturn();
assertEquals(stringWithSlashes, mvcResult.getResponse()
.getContentAsString());
}
@Test
public void givenAllFallbackEndpoint_whenUsingConsecutiveSlashes_thenPathNormalized() throws Exception {
final String stringWithSlashes = "http://myurl.com";
MvcResult mvcResult = mockMvc.perform(get("/slash/all/" + stringWithSlashes))
.andExpect(status().isOk())
.andReturn();
String stringWithSlashesNormalized = URI.create("/slash/all/" + stringWithSlashes)
.normalize()
.toString()
.split("/slash/all/")[1];
assertEquals(stringWithSlashesNormalized, mvcResult.getResponse()
.getContentAsString());
}
@Test
public void whenUsingSlashesInQueryParam_thenParameterAccepted() throws Exception {
final String stringWithSlashes = "url/for////testing/purposes";
MvcResult mvcResult = mockMvc.perform(get("/slash/all").param("param", stringWithSlashes))
.andExpect(status().isOk())
.andReturn();
assertEquals(stringWithSlashes, mvcResult.getResponse()
.getContentAsString());
}
}

View File

@@ -0,0 +1,83 @@
package com.baeldung.validation.listvalidation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
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;
import com.baeldung.validation.listvalidation.model.Movie;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringListValidationApplication.class)
@AutoConfigureMockMvc
public class MovieControllerIntegrationTest {
@Autowired
private MockMvc mvc;
ObjectMapper objectMapper = new ObjectMapper();
@Test
public void givenValidMovieList_whenAddingMovieList_thenIsOK() throws Exception {
List<Movie> movies = new ArrayList<>();
Movie movie = new Movie("Movie3");
movies.add(movie);
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(movies)))
.andExpect(MockMvcResultMatchers.status()
.isOk());
}
@Test
public void givenEmptyMovieList_whenAddingMovieList_thenThrowBadRequest() throws Exception {
List<Movie> movies = new ArrayList<>();
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(movies)))
.andExpect(MockMvcResultMatchers.status()
.isBadRequest());
}
@Test
public void givenEmptyMovieName_whenAddingMovieList_thenThrowBadRequest() throws Exception {
Movie movie = new Movie("");
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(Arrays.asList(movie))))
.andExpect(MockMvcResultMatchers.status()
.isBadRequest());
}
@Test
public void given5MoviesInputList_whenAddingMovieList_thenThrowBadRequest() throws Exception {
Movie movie1 = new Movie("Movie1");
Movie movie2 = new Movie("Movie2");
Movie movie3 = new Movie("Movie3");
Movie movie4 = new Movie("Movie4");
Movie movie5 = new Movie("Movie5");
List<Movie> movies = new ArrayList<>();
movies.add(movie1);
movies.add(movie2);
movies.add(movie3);
movies.add(movie4);
movies.add(movie5);
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(movies)))
.andExpect(MockMvcResultMatchers.status()
.isBadRequest());
}
}