JAVA-8294 : Split or move spring-data-rest module

This commit is contained in:
anuragkumawat
2022-01-19 21:43:54 +05:30
parent 616ada36a7
commit dbc1bf01e6
31 changed files with 364 additions and 115 deletions

View File

@@ -4,15 +4,12 @@ This module contains articles about Spring Data REST
### Relevant Articles:
- [Introduction to Spring Data REST](https://www.baeldung.com/spring-data-rest-intro)
- [Guide to Spring Data REST Validators](https://www.baeldung.com/spring-data-rest-validators)
- [Working with Relationships in Spring Data REST](https://www.baeldung.com/spring-data-rest-relationships)
- [AngularJS CRUD Application with Spring Data REST](https://www.baeldung.com/angularjs-crud-with-spring-data-rest)
- [Projections and Excerpts in Spring Data REST](https://www.baeldung.com/spring-data-rest-projections-excerpts)
- [Spring Data REST Events with @RepositoryEventHandler](https://www.baeldung.com/spring-data-rest-events)
- [Customizing HTTP Endpoints in Spring Data REST](https://www.baeldung.com/spring-data-rest-customize-http-endpoints)
- [Spring Boot with SQLite](https://www.baeldung.com/spring-boot-sqlite)
- [Spring Data Web Support](https://www.baeldung.com/spring-data-web-support)
- [Spring REST and HAL Browser](https://www.baeldung.com/spring-rest-hal)
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring

View File

@@ -33,15 +33,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-rest-hal-browser -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-explorer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>

View File

@@ -1,5 +1,7 @@
package com.baeldung.books.config;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
@@ -22,6 +24,11 @@ public class MvcConfig implements WebMvcConfigurer {
configurer.enable();
}
@Bean
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() {
return (factory) -> factory.setRegisterDefaultServlet(true);
}
@Bean
AuthorEventHandler authorEventHandler() {
return new AuthorEventHandler();

View File

@@ -1,14 +1,12 @@
package com.baeldung.books.config;
import com.baeldung.books.models.WebsiteUser;
import com.baeldung.books.projections.CustomBook;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.core.mapping.ExposureConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import com.baeldung.books.projections.CustomBook;
@Configuration
public class RestConfig implements RepositoryRestConfigurer {
@@ -16,7 +14,5 @@ public class RestConfig implements RepositoryRestConfigurer {
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration,
CorsRegistry cors) {
repositoryRestConfiguration.getProjectionConfiguration().addProjection(CustomBook.class);
ExposureConfiguration config = repositoryRestConfiguration.getExposureConfiguration();
config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) -> httpMethods.disable(HttpMethod.PATCH));
}
}

View File

@@ -1,30 +0,0 @@
package com.baeldung.books.config;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener;
import org.springframework.validation.Validator;
@Configuration
public class ValidatorEventRegister implements InitializingBean {
@Autowired
ValidatingRepositoryEventListener validatingRepositoryEventListener;
@Autowired
private Map<String, Validator> validators;
@Override
public void afterPropertiesSet() throws Exception {
List<String> events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete");
for (Map.Entry<String, Validator> entry : validators.entrySet()) {
events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
}
}
}

View File

@@ -1,11 +1,14 @@
package com.baeldung.books.events;
import org.springframework.data.rest.core.annotation.*;
import java.util.logging.Logger;
import org.springframework.data.rest.core.annotation.HandleAfterCreate;
import org.springframework.data.rest.core.annotation.HandleAfterDelete;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeDelete;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import com.baeldung.books.models.Author;
import com.baeldung.books.models.Book;
import java.util.logging.Logger;
@RepositoryEventHandler
public class AuthorEventHandler {

View File

@@ -2,8 +2,6 @@ package com.baeldung.books.events;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.springframework.data.rest.core.annotation.HandleAfterDelete;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;

View File

@@ -1,26 +0,0 @@
package com.baeldung.books.exception.handlers;
import org.springframework.data.rest.core.RepositoryConstraintViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.stream.Collectors;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ RepositoryConstraintViolationException.class })
public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) {
RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex;
String errors = nevEx.getErrors().getAllErrors().stream().map(ObjectError::toString).collect(Collectors.joining("\n"));
return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE);
}
}

View File

@@ -1,41 +0,0 @@
package com.baeldung.books.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class WebsiteUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@@ -1,33 +0,0 @@
package com.baeldung.books.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.baeldung.books.models.WebsiteUser;
@CrossOrigin
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends CrudRepository<WebsiteUser, Long> {
@Override
@RestResource(exported = false)
void delete(WebsiteUser entity);
@Override
@RestResource(exported = false)
void deleteAll();
@Override
@RestResource(exported = false)
void deleteAll(Iterable<? extends WebsiteUser> entities);
@Override
@RestResource(exported = false)
void deleteById(Long aLong);
@RestResource(path = "byEmail", rel = "customFindMethod")
WebsiteUser findByEmail(@Param("email") String email);
}

View File

@@ -1,33 +0,0 @@
package com.baeldung.books.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.baeldung.books.models.WebsiteUser;
@Component("beforeCreateWebsiteUserValidator")
public class WebsiteUserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return WebsiteUser.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
WebsiteUser user = (WebsiteUser) obj;
if (checkInputString(user.getName())) {
errors.rejectValue("name", "name.empty");
}
if (checkInputString(user.getEmail())) {
errors.rejectValue("email", "email.empty");
}
}
private boolean checkInputString(String input) {
return (input == null || input.trim().length() == 0);
}
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.halbrowser;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class);
}
}

View File

@@ -1,109 +0,0 @@
package com.baeldung.halbrowser.config;
import java.util.Random;
import java.util.stream.IntStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import com.baeldung.halbrowser.data.BookRepository;
import com.baeldung.halbrowser.model.Book;
@Component
public class DBLoader implements ApplicationRunner {
private final BookRepository bookRepository;
@Autowired
DBLoader(BookRepository bookRepository){
this.bookRepository = bookRepository;
}
public void run(ApplicationArguments applicationArguments) throws Exception {
String[] templates = {
"Up and running with %s",
"%s Basics",
"%s for Beginners",
"%s for Neckbeards",
"Under the hood: %s",
"Discovering %s",
"A short guide to %s",
"%s with Baeldung"
};
String[] buzzWords = {
"Spring REST Data",
"Java 9",
"Scala",
"Groovy",
"Hibernate",
"Spring HATEOS",
"The HAL Browser",
"Spring webflux",
};
String[] authorFirstName = {
"John %s",
"Steve %s",
"Samantha %s",
"Gale %s",
"Tom %s"
};
String[] authorLastName = {
"Giles",
"Gill",
"Smith",
"Armstrong"
};
String[] blurbs = {
"It was getting dark when the %s %s" ,
"Scott was nearly there when he heard that a %s %s",
"Diana was a lovable Java coder until the %s %s",
"The gripping story of a small %s and the day it %s"
};
String[] blublMiddles = {
"distaster",
"dog",
"cat",
"turtle",
"hurricane"
};
String[] end = {
"hit the school",
"memorised pi to 100 decimal places!",
"became a world champion armwrestler",
"became a Java REST master!!"
};
Random random = new Random();
IntStream.range(0, 100)
.forEach(i -> {
String template = templates[i % templates.length];
String buzzword = buzzWords[i % buzzWords.length];
String blurbStart = blurbs[i % blurbs.length];
String middle = blublMiddles[i % blublMiddles.length];
String ending = end[i % end.length];
String blurb = String.format(blurbStart, middle, ending);
String firstName = authorFirstName[i % authorFirstName.length];
String lastname = authorLastName[i % authorLastName.length];
Book book = new Book(String.format(template, buzzword), String.format(firstName, lastname), blurb, random.nextInt(1000-200) + 200);
bookRepository.save(book);
System.out.println(book);
});
}
}

View File

@@ -1,23 +0,0 @@
package com.baeldung.halbrowser.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.validation.Validator;
@Configuration
public class RestConfig implements RepositoryRestConfigurer {
//access to global validator
@Autowired
@Lazy
private Validator validator;
@Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
validatingListener.addValidator("beforeCreate", validator );
validatingListener.addValidator("beforeSave", validator);
}
}

View File

@@ -1,21 +0,0 @@
package com.baeldung.halbrowser.data;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;
import com.baeldung.halbrowser.model.Book;
@Repository
public interface BookRepository extends PagingAndSortingRepository<Book, Long> {
@RestResource(rel = "title-contains", path="title-contains")
Page<Book> findByTitleContaining(@Param("query") String query, Pageable page);
@RestResource(rel = "author-contains", path="author-contains", exported = false)
Page<Book> findByAuthorContaining(@Param("query") String query, Pageable page);
}

View File

@@ -1,86 +0,0 @@
package com.baeldung.halbrowser.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotNull
@Column(columnDefinition = "VARCHAR", length = 100)
private String title;
@NotNull
@Column(columnDefinition = "VARCHAR", length = 100)
private String author;
@Column(columnDefinition = "VARCHAR", length = 1000)
private String blurb;
private int pages;
public Book() {
}
public Book(@NotNull String title, @NotNull String author, String blurb, int pages) {
this.title = title;
this.author = author;
this.blurb = blurb;
this.pages = pages;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBlurb() {
return blurb;
}
public void setBlurb(String blurb) {
this.blurb = blurb;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", author='" + author + '\'' +
", blurb='" + blurb + '\'' +
", pages=" + pages +
'}';
}
}

View File

@@ -1,28 +0,0 @@
package com.baeldung.springdatawebsupport.application;
import com.baeldung.springdatawebsupport.application.entities.User;
import com.baeldung.springdatawebsupport.application.repositories.UserRepository;
import java.util.stream.Stream;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner initialize(UserRepository userRepository) {
return args -> {
Stream.of("John", "Robert", "Nataly", "Helen", "Mary").forEach(name -> {
User user = new User(name);
userRepository.save(user);
});
userRepository.findAll().forEach(System.out::println);
};
}
}

View File

@@ -1,47 +0,0 @@
package com.baeldung.springdatawebsupport.application.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.springdatawebsupport.application.entities.User;
import com.baeldung.springdatawebsupport.application.repositories.UserRepository;
import com.querydsl.core.types.Predicate;
@RestController
public class UserController {
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/users/{id}")
public User findUserById(@PathVariable("id") User user) {
return user;
}
@GetMapping("/users")
public Page<User> findAllUsers(Pageable pageable) {
return userRepository.findAll(pageable);
}
@GetMapping("/sortedusers")
public Page<User> findAllUsersSortedByName() {
Pageable pageable = PageRequest.of(0, 5, Sort.by("name"));
return userRepository.findAll(pageable);
}
@GetMapping("/filteredusers")
public Iterable<User> getUsersByQuerydslPredicate(@QuerydslPredicate(root = User.class) Predicate predicate) {
return userRepository.findAll(predicate);
}
}

View File

@@ -1,38 +0,0 @@
package com.baeldung.springdatawebsupport.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private final String name;
public User() {
this.name = "";
}
public User(String name) {
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + '}';
}
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.springdatawebsupport.application.repositories;
import com.baeldung.springdatawebsupport.application.entities.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long>, QuerydslPredicateExecutor<User> {
}

View File

@@ -1,118 +0,0 @@
package com.baeldung.books.validator;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
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.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.books.SpringDataRestApplication;
import com.baeldung.books.models.WebsiteUser;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class SpringDataRestValidatorIntegrationTest {
public static final String URL = "http://localhost";
@Autowired
private MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
mockMvc = webAppContextSetup(wac).build();
}
@Test
public void whenStartingApplication_thenCorrectStatusCode() throws Exception {
mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful());
};
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
user.setName("John Doe");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().is2xxSuccessful()).andExpect(redirectedUrl("http://localhost/users/1"));
}
@Test
public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null));
}
@Test
public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
user.setName("");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null));
}
@Test
public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setName("John Doe");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null));
}
@Test
public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setName("John Doe");
user.setEmail("");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null));
}
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void whenDeletingCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
user.setName("John Doe");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().is2xxSuccessful()).andExpect(redirectedUrl("http://localhost/users/1"));
mockMvc.perform(delete("/users/1").contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isMethodNotAllowed());
}
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void whenSearchingByEmail_thenCorrectStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
user.setName("John Doe");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().is2xxSuccessful()).andExpect(redirectedUrl("http://localhost/users/1"));
mockMvc.perform(get("/users/search/byEmail").param("email", user.getEmail()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().is2xxSuccessful());
}
@Test
public void whenSearchingByEmailWithOriginalMethodName_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
user.setName("John Doe");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().is2xxSuccessful()).andExpect(redirectedUrl("http://localhost/users/1"));
mockMvc.perform(get("/users/search/findByEmail").param("email", user.getEmail()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound());
}
}

View File

@@ -1,58 +0,0 @@
package com.baeldung.springdatawebsupport.application.test;
import com.baeldung.springdatawebsupport.application.controllers.UserController;
import static org.assertj.core.api.Assertions.assertThat;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {
@Autowired
private UserController userController;
@Autowired
private MockMvc mockMvc;
@Test
public void whenUserControllerInjected_thenNotNull() throws Exception {
assertThat(userController).isNotNull();
}
@Test
public void whenGetRequestToUsersEndPointWithIdPathVariable_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users/{id}", "1").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
}
@Test
public void whenGetRequestToUsersEndPoint_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$['pageable']['paged']").value("true"));
}
@Test
public void whenGetRequestToUserEndPointWithNameRequestParameter_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$['content'][0].['name']").value("John"));
}
@Test
public void whenGetRequestToSorteredUsersEndPoint_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/sortedusers").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$['sort']['sorted']").value("true"));
}
@Test
public void whenGetRequestToFilteredUsersEndPoint_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/filteredusers").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("John"));
}
}