2023-09 spring-17-mvc added

This commit is contained in:
stvort
2023-12-07 20:02:40 +04:00
parent 135f8ab4cb
commit 88be7699c3
48 changed files with 1858 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-class-work</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>spring-mvc-exercise</module>
<module>spring-mvc-solution-1</module>
<module>spring-mvc-solution-2</module>
<module>spring-mvc-solution-3</module>
<module>spring-mvc-demo</module>
</modules>
</project>
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-demo</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,28 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@SpringBootApplication
public class Main {
// http://localhost:8080/server/system/info
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,21 @@
package ru.otus.spring.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import ru.otus.spring.rest.resolvers.SystemInfoMethodArgumentResolver;
import java.util.List;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private SystemInfoMethodArgumentResolver systemInfoMethodArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(systemInfoMethodArgumentResolver);
}
}
@@ -0,0 +1,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
@@ -0,0 +1,31 @@
package ru.otus.spring.domain;
public class SystemInfo {
private final String osName;
private final String timeZone;
private final String osArch;
private final int processorsCount;
public SystemInfo(String osName, String timeZone, String osArch, int processorsCount) {
this.osName = osName;
this.timeZone = timeZone;
this.osArch = osArch;
this.processorsCount = processorsCount;
}
public String getOsName() {
return osName;
}
public String getTimeZone() {
return timeZone;
}
public String getOsArch() {
return osArch;
}
public int getProcessorsCount() {
return processorsCount;
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,64 @@
package ru.otus.spring.rest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.rest.exceptions.NotFoundException;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET, params = "name")
public PersonDto getPersonByNameInRequest(@RequestParam("name") String name) {
Person person = repository.findByName(name).stream().findFirst().orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@GetMapping("/persons/{id}")
public PersonDto getPersonByIdInPath(@PathVariable("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@PostMapping("/persons")
public PersonDto createNewPerson(@RequestBody PersonDto dto) {
Person person = PersonDto.toDomainObject(dto);
Person savedPerson = repository.save(person);
return PersonDto.toDto(savedPerson);
}
@PatchMapping("/persons/{id}/name")
public PersonDto updateNameById(@PathVariable("id") long id, @RequestParam("name") String name) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
person.setName(name);
return PersonDto.toDto(repository.save(person));
}
@DeleteMapping("/persons/{id}")
public void deleteById(@PathVariable("id") long id) {
repository.deleteById(id);
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<String> handleNotFound(NotFoundException ex) {
return ResponseEntity.badRequest().body("Таких тут нет!");
}
}
@@ -0,0 +1,14 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.otus.spring.domain.SystemInfo;
@RestController
public class SystemInfoController {
@GetMapping("/server/system/info")
public SystemInfo getServerSystemInfo(SystemInfo systemInfo) {
return systemInfo;
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
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 static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,33 @@
package ru.otus.spring.rest.resolvers;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import ru.otus.spring.domain.SystemInfo;
import ru.otus.spring.service.SystemInfoService;
@Component
public class SystemInfoMethodArgumentResolver implements HandlerMethodArgumentResolver {
private final SystemInfoService systemInfoService;
public SystemInfoMethodArgumentResolver(SystemInfoService systemInfoService) {
this.systemInfoService = systemInfoService;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(SystemInfo.class);
}
@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
return systemInfoService.getSystemInfo();
}
}
@@ -0,0 +1,17 @@
package ru.otus.spring.service;
import org.springframework.stereotype.Service;
import ru.otus.spring.domain.SystemInfo;
@Service
public class SystemInfoService {
public SystemInfo getSystemInfo(){
String osName = System.getProperty("os.name");
String timeZone = System.getProperty("user.timezone");
String osArch = System.getProperty("os.arch");
int processorsCount = Runtime.getRuntime().availableProcessors();
return new SystemInfo(osName, timeZone, osArch, processorsCount);
}
}
@@ -0,0 +1,127 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.service.SystemInfoService;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@MockBean
private SystemInfoService systemInfoService;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
@Test
void shouldCorrectSaveNewPerson() throws Exception {
Person person = new Person(1, "Person1");
given(repository.save(any())).willReturn(person);
String expectedResult = mapper.writeValueAsString(PersonDto.toDto(person));
mvc.perform(post("/persons").contentType(APPLICATION_JSON)
.content(expectedResult))
.andExpect(status().isOk())
.andExpect(content().json(expectedResult));
}
@Test
void shouldCorrectUpdatePersonName() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
given(repository.save(any())).willAnswer(invocation -> invocation.getArgument(0));
Person expectedPerson = new Person(1, "Person2");
String expectedResult = mapper.writeValueAsString(PersonDto.toDto(expectedPerson));
mvc.perform(patch("/persons/{id}/name", 1).param("name", expectedPerson.getName())
.content(expectedResult))
.andExpect(status().isOk())
.andExpect(content().json(expectedResult));
}
@Test
void shouldCorrectDeletePerson() throws Exception {
mvc.perform(delete("/persons/1"))
.andExpect(status().isOk());
verify(repository, times(1)).deleteById(1L);
}
}
@@ -0,0 +1,39 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.SystemInfo;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.service.SystemInfoService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@WebMvcTest(SystemInfoController.class)
@Import(SystemInfoService.class)
class SystemInfoControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Autowired
private SystemInfoService systemInfoService;
@Test
void shouldReturnCorrectServerSystemInfo() throws Exception {
SystemInfo expectedSystemInfo = systemInfoService.getSystemInfo();
mvc.perform(get("/server/system/info"))
.andExpect(content().json(mapper.writeValueAsString(expectedSystemInfo)));
}
}
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-exercise</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,13 @@
package ru.otus.spring.rest;
import ru.otus.spring.repostory.PersonRepository;
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
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 static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exeptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-solution-1</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,27 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
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 static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-solution-2</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,40 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.rest.exceptions.NotFoundException;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET, params = "name")
public PersonDto getPersonByNameInRequest(@RequestParam("name") String name) {
Person person = repository.findByName(name).stream().findFirst().orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@GetMapping("/persons/{id}")
public PersonDto getPersonByIdInPath(@PathVariable("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
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 static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
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;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-solution-3</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,10 @@
POST http://localhost:8080/person
Content-Type: application/json
{
"id": "2",
"name": "Pushkin"
}
###
GET http://localhost:8080/persons/all
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,45 @@
package ru.otus.spring.rest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.rest.exceptions.NotFoundException;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET, params = "name")
public PersonDto getPersonByNameInRequest(@RequestParam("name") String name) {
Person person = repository.findByName(name).stream().findFirst().orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@GetMapping("/persons/{id}")
public PersonDto getPersonByIdInPath(@PathVariable("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<String> handleNotFound(NotFoundException ex) {
return ResponseEntity.badRequest().body("Таких тут нет!");
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
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 static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
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;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}