diff --git a/src/main/java/com/example/demo/config/utils/BaseTime.java b/src/main/java/com/example/demo/config/utils/BaseTime.java index edbd9c70..26e578de 100644 --- a/src/main/java/com/example/demo/config/utils/BaseTime.java +++ b/src/main/java/com/example/demo/config/utils/BaseTime.java @@ -1,5 +1,6 @@ package com.example.demo.config.utils; +import org.hibernate.annotations.ColumnDefault; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @@ -15,8 +16,13 @@ public abstract class BaseTime { @CreatedDate @Column(nullable = false) - private LocalTime createdAt; + private LocalDateTime createdAt; @LastModifiedDate private LocalDateTime updatedAt; + + private LocalDateTime deletedAt; + + @ColumnDefault("false") + private boolean isDeleted; } diff --git a/src/main/java/com/example/demo/interest/Interest.java b/src/main/java/com/example/demo/interest/Interest.java index 67048693..84dbb3f1 100644 --- a/src/main/java/com/example/demo/interest/Interest.java +++ b/src/main/java/com/example/demo/interest/Interest.java @@ -1,5 +1,6 @@ package com.example.demo.interest; +import com.example.demo.config.utils.BaseTime; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; @@ -11,7 +12,7 @@ @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity @Table(name = "interest_tb") -public class Interest { +public class Interest extends BaseTime { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; diff --git a/src/main/java/com/example/demo/mentoring/MentorPost.java b/src/main/java/com/example/demo/mentoring/MentorPost.java index a8709fb2..1d5c9feb 100644 --- a/src/main/java/com/example/demo/mentoring/MentorPost.java +++ b/src/main/java/com/example/demo/mentoring/MentorPost.java @@ -6,12 +6,16 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import org.hibernate.annotations.SQLDelete; +import org.hibernate.annotations.Where; import javax.persistence.*; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity +@Where(clause = "deleted_at IS NULL") +@SQLDelete(sql = "UPDATE mentorPost_tb SET deleted_at = CURRENT_TIMESTAMP, isDeleted = TRUE where id = ?") @Table(name = "mentorPost_tb") public class MentorPost extends BaseTime { @Id @@ -32,4 +36,11 @@ public MentorPost(User writer, String title, String content){ this.title = title; this.content = content; } + + public void update(String title, String content) + { + this.title = title; + this.content = content; + } + } diff --git a/src/main/java/com/example/demo/mentoring/MentorPostRequest.java b/src/main/java/com/example/demo/mentoring/MentorPostRequest.java index 96434478..a95762ec 100644 --- a/src/main/java/com/example/demo/mentoring/MentorPostRequest.java +++ b/src/main/java/com/example/demo/mentoring/MentorPostRequest.java @@ -9,18 +9,10 @@ public class MentorPostRequest { @Getter @Setter - public class CreateDTO { + public static class CreateDTO { @NotNull private String title; private String content; - - public MentorPost toEntity(User writer) { - return MentorPost.builder() - .writer(writer) - .title(title) - .content(content) - .build(); - } } } diff --git a/src/main/java/com/example/demo/mentoring/MentorPostResponse.java b/src/main/java/com/example/demo/mentoring/MentorPostResponse.java index d5c81b97..0343f3e5 100644 --- a/src/main/java/com/example/demo/mentoring/MentorPostResponse.java +++ b/src/main/java/com/example/demo/mentoring/MentorPostResponse.java @@ -1,6 +1,7 @@ package com.example.demo.mentoring; +import com.example.demo.mentoring.contact.NotConnectedRegisterUser; import com.example.demo.user.Role; import com.example.demo.user.User; import com.example.demo.user.userInterest.UserInterest; @@ -12,6 +13,61 @@ public class MentorPostResponse { +/* + 페이지에서 멘토post 전체를 조회 + MentorPostAllDTO + 클릭시 들어간 페이지에서 보여지는 Post + MentorPostDTO + */ + @Getter + @Setter + public static class MentorPostAllDTO { + private int postId; + private String title; + private String content; + private WriterDTO writerDTO; + + public MentorPostAllDTO(MentorPost mentorPost, List userInterests) { + this.postId = mentorPost.getId(); + this.title = mentorPost.getTitle(); + this.content = mentorPost.getContent(); + WriterDTO writerDTO = new MentorPostAllDTO.WriterDTO(mentorPost.getWriter(), userInterests); + this.writerDTO = writerDTO; + } + + @Getter @Setter + public static class WriterDTO { + private int mentorId; + private String profileImage; + private String name; + private String country; + private Role role; + private List interests; + + public WriterDTO(User user, List userInterests) { + this.mentorId = user.getId(); + this.profileImage = user.getProfileImage(); + this.name = user.getFirstName() + " " + user.getLastName(); + this.country = user.getCountry(); + this.role = user.getRole(); + this.interests = userInterests.stream() + .map(userInterest -> userInterest.getInterest().getCategory()) + .collect(Collectors.toList()); + } + } + } + + /* + param : + MentorPost mentorPost 멘토 데이터 + List mentorInterests 멘토의 Interest + List mentees 멘티들 데이터 + List menteeInterests : 멘티들 각각의 Interest 리스트 전체 + + dto : + writerDTO : 작성자인 멘토의 DTO + menteeDTO : 멘티들의 DTO + */ @Getter @Setter public static class MentorPostDTO { @@ -19,12 +75,25 @@ public static class MentorPostDTO { private String title; private String content; private WriterDTO writerDTO; + private List menteeDTOList; - public MentorPostDTO(MentorPost mentorPost, WriterDTO writerDTO) { + public MentorPostDTO(MentorPost mentorPost, List mentorFavorites, List mentees, List menteeInterest) { this.postId = mentorPost.getId(); this.title = mentorPost.getTitle(); this.content = mentorPost.getContent(); + MentorPostDTO.WriterDTO writerDTO = new MentorPostDTO.WriterDTO(mentorPost.getWriter(), mentorFavorites); this.writerDTO = writerDTO; + List menteeDTOList = mentees.stream() + .map(mentee -> { + List eachMenteeFavorite = menteeInterest.stream().filter( + userInterest -> mentee.getMenteeUser().getId() == userInterest.getUser().getId() + ).collect(Collectors.toList()); + + MentorPostDTO.MenteeDTO menteeDTO = new MentorPostDTO.MenteeDTO(mentee.getMenteeUser(), eachMenteeFavorite); + return menteeDTO; + }) + .collect(Collectors.toList()); + this.menteeDTOList = menteeDTOList; } @Getter @Setter @@ -34,7 +103,7 @@ public static class WriterDTO { private String name; private String country; private Role role; - private List favorites; + private List interests; public WriterDTO(User user, List userInterests) { this.mentorId = user.getId(); @@ -42,8 +111,30 @@ public WriterDTO(User user, List userInterests) { this.name = user.getFirstName() + " " + user.getLastName(); this.country = user.getCountry(); this.role = user.getRole(); - this.favorites = userInterests.stream() - .filter(userInterest -> userInterest.getUser().getId() == user.getId()) + this.interests = userInterests.stream() + .map(userInterest -> userInterest.getInterest().getCategory()) + .collect(Collectors.toList()); + } + } + + @Getter @Setter + public static class MenteeDTO{ + private int menteeId; + private String profileImage; + private String name; + private String country; + private Role role; + private int age; + private List interests; + + public MenteeDTO(User user, List userInterests) { + this.menteeId = user.getId(); + this.profileImage = user.getProfileImage(); + this.name = user.getFirstName() + " " + user.getLastName(); + this.country = user.getCountry(); + this.role = user.getRole(); + this.age = user.getAge(); + this.interests = userInterests.stream() .map(userInterest -> userInterest.getInterest().getCategory()) .collect(Collectors.toList()); } diff --git a/src/main/java/com/example/demo/mentoring/MentorPostRestController.java b/src/main/java/com/example/demo/mentoring/MentorPostRestController.java index 2654e342..2d8d3465 100644 --- a/src/main/java/com/example/demo/mentoring/MentorPostRestController.java +++ b/src/main/java/com/example/demo/mentoring/MentorPostRestController.java @@ -3,21 +3,40 @@ import com.example.demo.config.auth.CustomUserDetails; import com.example.demo.config.utils.ApiUtils; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.validation.Errors; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + +import java.util.List; @RequiredArgsConstructor @RestController public class MentorPostRestController { private final MentorPostService mentorPostService; - @PostMapping(value = "/mentorings") + @PostMapping(value = "/mentorings/post") public ResponseEntity createMentorPost(@RequestPart MentorPostRequest.CreateDTO requestDTO, Errors errors, @AuthenticationPrincipal CustomUserDetails userDetails) { mentorPostService.createMentorPost(requestDTO, userDetails.getUser()); - return ResponseEntity.ok().body(ApiUtils.success(true)); + return ResponseEntity.status(HttpStatus.OK).body(ApiUtils.successWithNoContent()); + } + + @GetMapping("/mentorings/post") + public ResponseEntity getMentorPost(@RequestParam(value = "page", defaultValue = "0") Integer page, @AuthenticationPrincipal CustomUserDetails userDetails) { + List responseDTOs = mentorPostService.findAllMentorPost(page); + return ResponseEntity.ok(ApiUtils.success(responseDTOs)); + } + + @GetMapping("/mentorings/post/{id}") + public ResponseEntity getMentorPostId(@PathVariable int id, @AuthenticationPrincipal CustomUserDetails userDetails) { + MentorPostResponse.MentorPostDTO responseDTO = mentorPostService.findMentorPost(id); + return ResponseEntity.ok(ApiUtils.success(responseDTO)); + } + + @PutMapping(value = "/mentorings/post/{id}") + public ResponseEntity updateMentorPost(@PathVariable int id, @RequestPart MentorPostRequest.CreateDTO requestDTO, Errors errors, @AuthenticationPrincipal CustomUserDetails userDetails) { + mentorPostService.updateMentorPost(requestDTO, id); + return ResponseEntity.status(HttpStatus.OK).body(ApiUtils.successWithNoContent()); } } diff --git a/src/main/java/com/example/demo/mentoring/MentorPostService.java b/src/main/java/com/example/demo/mentoring/MentorPostService.java index 84957e60..82593bbb 100644 --- a/src/main/java/com/example/demo/mentoring/MentorPostService.java +++ b/src/main/java/com/example/demo/mentoring/MentorPostService.java @@ -1,40 +1,87 @@ package com.example.demo.mentoring; +import com.example.demo.mentoring.contact.ContactJPARepository; +import com.example.demo.mentoring.contact.NotConnectedRegisterUser; import com.example.demo.user.User; import com.example.demo.user.userInterest.UserInterest; import com.example.demo.user.userInterest.UserInterestJPARepository; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @Transactional @RequiredArgsConstructor @Service public class MentorPostService { - private final MentorPostJPARepostiory mentorPostJPARepostiory; + private final MentorPostJPARepostiory mentorPostJPARepository; private final UserInterestJPARepository userInterestJPARepository; + private final ContactJPARepository contactJPARepository; //mentorPost생성 @Transactional public void createMentorPost(MentorPostRequest.CreateDTO createDTO, User writer) { - mentorPostJPARepostiory.save(createDTO.toEntity(writer)); + MentorPost mentorPost = new MentorPost( writer, createDTO.getTitle(), createDTO.getContent()); + mentorPostJPARepository.save(mentorPost); } /* 1. mentorPostList를 조회 2. 각 List당 writer별 writerInterests를 조회 3. MentorPostDTO 생성*/ - public List findAllMentorPost() { - List mentorPostList = mentorPostJPARepostiory.findAll(); - List mentorPostDTOList = mentorPostList.stream().map( + public List findAllMentorPost(int page) { + Pageable pageable = PageRequest.of(page,5); + + Page pageContent = mentorPostJPARepository.findAll(pageable); + //List mentorPostList = mentorPostJPARepostiory.findAll(); + List mentorPostDTOList = pageContent.getContent().stream().map( mentorPost -> { List writerInterests = userInterestJPARepository.findAllById(mentorPost.getWriter().getId()); - MentorPostResponse.MentorPostDTO.WriterDTO writerDTO = new MentorPostResponse.MentorPostDTO.WriterDTO(mentorPost.getWriter(), writerInterests); - return new MentorPostResponse.MentorPostDTO(mentorPost,writerDTO); + return new MentorPostResponse.MentorPostAllDTO(mentorPost,writerInterests); } ).collect(Collectors.toList()); return mentorPostDTOList; } + + public MentorPostResponse.MentorPostDTO findMentorPost(int id){ + MentorPost mentorPost = mentorPostJPARepository.findById(id); + + //writer 데이터 + User mentor = mentorPost.getWriter(); + //mentee들 데이터 + List menteeList = contactJPARepository.findAllByMentorPostId(id); + //writer Interest데이터 + List mentorInterests = userInterestJPARepository.findAllById(mentor.getId()); + //mentee들 Interest데이터 + List menteeInterests = menteeList.stream() + .flatMap(mentee -> userInterestJPARepository.findAllById(mentee.getMenteeUser().getId()).stream()) + .collect(Collectors.toList()); + + MentorPostResponse.MentorPostDTO mentorPostDTO = new MentorPostResponse.MentorPostDTO(mentorPost, mentorInterests, menteeList, menteeInterests); + + return mentorPostDTO; + } + @Transactional + public void updateMentorPost(MentorPostRequest.CreateDTO createDTO, int id) + { + Optional optionalMentorPost = Optional.ofNullable(mentorPostJPARepository.findById(id)); + + if(optionalMentorPost.isPresent()) + { + MentorPost mentorPost = optionalMentorPost.get(); + mentorPost.update(createDTO.getTitle(), createDTO.getContent()); + } + else + { + // 예외처리 + + } + } } + + diff --git a/src/main/java/com/example/demo/mentoring/contact/NotConnectedRegisterUser.java b/src/main/java/com/example/demo/mentoring/contact/NotConnectedRegisterUser.java index 62b945fc..b4537021 100644 --- a/src/main/java/com/example/demo/mentoring/contact/NotConnectedRegisterUser.java +++ b/src/main/java/com/example/demo/mentoring/contact/NotConnectedRegisterUser.java @@ -26,6 +26,8 @@ public class NotConnectedRegisterUser extends BaseTime { @ManyToOne(fetch = FetchType.LAZY) private User menteeUser; + @Column(nullable = false) + @Enumerated(value = EnumType.STRING) private State state; public enum State { diff --git a/src/main/resources/db/teardown.sql b/src/main/resources/db/teardown.sql new file mode 100644 index 00000000..949b96e4 --- /dev/null +++ b/src/main/resources/db/teardown.sql @@ -0,0 +1,60 @@ +SET REFERENTIAL_INTEGRITY FALSE; +TRUNCATE TABLE user_tb; +TRUNCATE TABLE interest_tb; +TRUNCATE TABLE mentor_post_tb; +TRUNCATE TABLE user_interest_tb; +TRUNCATE TABLE not_connected_register_user_tb; +SET REFERENTIAL_INTEGRITY TRUE; + +-- user Table +INSERT INTO user_tb (created_at, first_name, last_name, email, password, country, introduction, age, profile_image, role) VALUES + (NOW(), 'John', 'Doe', 'john@example.com', '{bcrypt}$2a$10$8H0OT8wgtALJkig6fmypi.Y7jzI5Y7W9PGgRKqnVeS2cLWGifwHF2', 'USA', 'Hello, I am John.', 25, 'profile.jpg', 'MENTOR'), + (NOW(), 'Alice', 'Smith', 'alice.smith@example.com', '{bcrypt}$2a$10$8H0OT8wgtALJkig6fmypi.Y7jzI5Y7W9PGgRKqnVeS2cLWGifwHF2', 'Canada', 'I love painting.', 25, 'image2.jpg', 'MENTOR'), + (NOW(), 'Admin', 'Admin', 'admin@example.com', '{bcrypt}$2a$10$8H0OT8wgtALJkig6fmypi.Y7jzI5Y7W9PGgRKqnVeS2cLWGifwHF2', 'USA', 'I am an admin user.', 35, 'admin.jpg', 'MENTEE'), + (NOW(), 'Jane', 'Smith', 'jane@example.com', '{bcrypt}$2a$10$8H0OT8wgtALJkig6fmypi.Y7jzI5Y7W9PGgRKqnVeS2cLWGifwHF2', 'Canada', 'I love coding.', 30, 'profile.jpg', 'MENTEE'), + (NOW(), 'Admin', 'Adminson', 'admin22222@example.com', '{bcrypt}$2a$10$8H0OT8wgtALJkig6fmypi.Y7jzI5Y7W9PGgRKqnVeS2cLWGifwHF2', 'USA', 'I am the admin.', 35, 'admin.jpg', 'MENTEE'); + +-- interst Table +INSERT INTO interest_tb (created_at, category) VALUES + (NOW(), 'IDOL'), + (NOW(), 'Game'), + (NOW(), 'K-POP'), + (NOW(), 'Sports'); + +-- mentorPost Table +INSERT INTO mentor_post_tb (created_at, writer_id, title, content) VALUES + (NOW(), 1, 'Teaching Programming', 'I can teach you how to code.'), + (NOW(), 1, 'Art Workshop', 'Let''s create beautiful art together.'), + (NOW(), 2, 'Software Development Mentorship', 'I can mentor you in software development.'), + (NOW(), 2, 'Art and Painting Mentorship', 'Learn the art of painting with me.'), + (NOW(), 1, 'Web Development Mentorship', 'I can teach you web development from scratch.'), + (NOW(), 2, 'Fitness and Health Mentorship', 'Get in shape and stay healthy with my guidance.'), + (NOW(), 1, 'Data Science Mentorship', 'Learn data science and machine learning with me.'), + (NOW(), 2, 'Music Production Mentorship', 'Produce your own music with professional tips.'), + (NOW(), 2, 'Cooking and Culinary Arts Mentorship', 'Master the art of cooking and culinary skills.'), + (NOW(), 2, 'Entrepreneurship Mentorship', 'Start and grow your own business.'), + (NOW(), 1, 'Graphic Design Mentorship', 'Create stunning graphics and designs.'), + (NOW(), 1, 'Yoga and Mindfulness Mentorship', 'Find inner peace and balance through yoga.'), + (NOW(), 1, 'Photography Mentorship', 'Capture amazing moments with your camera.'), + (NOW(), 2, 'Mathematics Tutoring', 'I can help you understand and excel in math.');; + + +-- notConnectedRegisterUser Table +INSERT INTO not_connected_register_user_tb (created_at, mentor_post_id, mentee_user_id, state) VALUES + (NOW(), 1, 3, 'AWAIT'), + (NOW(), 1, 4, 'ACCEPT'), + (NOW(), 2, 5, 'AWAIT'); + +-- userInterest Table +INSERT INTO user_interest_tb (created_at, user_id, interest_id) VALUES + (NOW(), 1, 1), + (NOW(), 1, 2), + (NOW(), 2, 1), + (NOW(), 2, 3), + (NOW(), 3, 3), + (NOW(), 3, 4), + (NOW(), 4, 1), + (NOW(), 4, 3), + (NOW(), 5, 3), + (NOW(), 5, 4) +; \ No newline at end of file diff --git a/src/test/java/com/example/demo/GardenBeApplicationTests.java b/src/test/java/com/example/demo/GardenBeApplicationTests.java index 4da8df8c..0c5a59c6 100644 --- a/src/test/java/com/example/demo/GardenBeApplicationTests.java +++ b/src/test/java/com/example/demo/GardenBeApplicationTests.java @@ -3,9 +3,11 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.jdbc.Sql; @SpringBootTest @ActiveProfiles("test") +@Sql("classpath:db/teardown.sql") class GardenBeApplicationTests { @Test diff --git a/src/test/java/com/example/demo/RestDoc.java b/src/test/java/com/example/demo/RestDoc.java new file mode 100644 index 00000000..dea8bb38 --- /dev/null +++ b/src/test/java/com/example/demo/RestDoc.java @@ -0,0 +1,37 @@ +package com.example.demo; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; +import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; +import org.springframework.restdocs.operation.preprocess.Preprocessors; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; + +import java.nio.charset.StandardCharsets; + +@ExtendWith({ SpringExtension.class, RestDocumentationExtension.class }) +public class RestDoc { + protected MockMvc mvc; + protected RestDocumentationResultHandler document; + + @BeforeEach + private void setup(WebApplicationContext webApplicationContext, + RestDocumentationContextProvider restDocumentation) { + this.document = MockMvcRestDocumentation.document("{class-name}/{method-name}", + Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), + Preprocessors.preprocessResponse(Preprocessors.prettyPrint())); + + mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .addFilter(new CharacterEncodingFilter(StandardCharsets.UTF_8.name(), true)) + .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation)) + // .apply(SecurityMockMvcConfigurers.springSecurity()) + .alwaysDo(document) + .build(); + } +} diff --git a/src/test/java/com/example/demo/mentoringtest/MentoringTest.java b/src/test/java/com/example/demo/mentoringtest/MentoringTest.java index 03693896..6af5632e 100644 --- a/src/test/java/com/example/demo/mentoringtest/MentoringTest.java +++ b/src/test/java/com/example/demo/mentoringtest/MentoringTest.java @@ -1,33 +1,53 @@ package com.example.demo.mentoringtest; -import com.example.demo.mentoring.MentorPost; -import com.example.demo.mentoring.MentorPostJPARepostiory; -import com.example.demo.mentoring.MentorPostResponse; -import com.example.demo.mentoring.MentorPostService; +import com.example.demo.RestDoc; +import com.example.demo.interest.Interest; +import com.example.demo.interest.InterestJPARepository; +import com.example.demo.mentoring.*; +import com.example.demo.mentoring.contact.ContactJPARepository; +import com.example.demo.mentoring.contact.NotConnectedRegisterUser; import com.example.demo.user.Role; import com.example.demo.user.User; import com.example.demo.user.UserJPARepository; +import com.example.demo.user.userInterest.UserInterest; +import com.example.demo.user.userInterest.UserInterestJPARepository; import com.fasterxml.jackson.databind.ObjectMapper; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; 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.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.web.servlet.ResultActions; -import java.util.List; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @SpringBootTest +@AutoConfigureMockMvc @ActiveProfiles("test") -public class MentoringTest { +public class MentoringTest extends RestDoc { @Autowired private UserJPARepository userJPARepository; @Autowired private MentorPostJPARepostiory mentorPostJPARepostiory; - + @Autowired + private InterestJPARepository interestJPARepository; @Autowired private MentorPostService mentorPostService; + @Autowired + private UserInterestJPARepository userInterestJPARepository; + @Autowired + private ContactJPARepository contactJPARepository; @Autowired private ObjectMapper om; @@ -55,23 +75,231 @@ void CreateMentorPostTest() { .content("content") .build(); + MentorPost mentorPost2 = MentorPost.builder() + .writer(writer) + .title("title2") + .content("content2") + .build(); + // then +// userJPARepository.save(writer); +// mentorPostJPARepostiory.save(mentorPost); +// mentorPostJPARepostiory.save(mentorPost2); + userJPARepository.save(writer); - mentorPostJPARepostiory.save(mentorPost); + MentorPostRequest.CreateDTO mentorPostRequest = new MentorPostRequest.CreateDTO(); + mentorPostRequest.setTitle("title"); + mentorPostRequest.setContent("content"); + mentorPostService.createMentorPost(mentorPostRequest, writer); - MentorPost mentorPostFind = mentorPostJPARepostiory.findById(mentorPost.getId()); - Assertions.assertThat(mentorPost.getId()) + MentorPost mentorPostFind = mentorPostJPARepostiory.findById(1); + Assertions.assertThat(1) .isEqualTo(mentorPostFind.getId()); + Assertions.assertThat(mentorPostRequest.getTitle()) + .isEqualTo(mentorPostFind.getTitle()); + Assertions.assertThat(mentorPostRequest.getContent()) + .isEqualTo(mentorPostFind.getContent()); + } + + + + @Test + @DisplayName("findMentorPostTest") + void findMentorPostSaveTest() { + //given + User mentor = User.builder() + .email("anjdal6612312364@gmail.com") + .password("as123df1234!") + .firstName("Jin123") + .lastName("Seun123g") + .country("Korea") + .age(21) + .role(Role.MENTOR) + .build(); + + User mentee_One = User.builder() + .email("anjda22l6664@gmail.com") + .password("asdf221234!") + .firstName("mentee1") + .lastName("Seung11") + .country("Korea") + .age(21) + .role(Role.MENTEE) + .build(); + + User mentee_Two = User.builder() + .email("anjdal66111164@gmail.com") + .password("asdf122222234!") + .firstName("mentee2") + .lastName("Seung22") + .country("Korea") + .age(21) + .role(Role.MENTEE) + .build(); + + Interest interest1 = Interest.builder() + .category("test1") + .build(); + + Interest interest2 = Interest.builder() + .category("test2") + .build(); + + Interest interest3 = Interest.builder() + .category("test3") + .build(); + + UserInterest userInterest1 = UserInterest.builder() + .user(mentor) + .interest(interest2) + .build(); + + UserInterest userInterest2 = UserInterest.builder() + .user(mentee_One) + .interest(interest2) + .build(); + + UserInterest userInterest3 = UserInterest.builder() + .user(mentee_One) + .interest(interest3) + .build(); + + UserInterest userInterest4 = UserInterest.builder() + .user(mentee_Two) + .interest(interest1) + .build(); + + UserInterest userInterest5 = UserInterest.builder() + .user(mentee_Two) + .interest(interest2) + .build(); + + UserInterest userInterest6 = UserInterest.builder() + .user(mentor) + .interest(interest3) + .build(); + + MentorPost mentorPost3 = MentorPost.builder() + .writer(mentor) + .title("title") + .content("content") + .build(); + + NotConnectedRegisterUser menteeNotConnected1 = NotConnectedRegisterUser.builder() + .mentorPost(mentorPost3) + .menteeUser(mentee_One) + .state(NotConnectedRegisterUser.State.AWAIT) + .build(); + + NotConnectedRegisterUser menteeNotConnected2 = NotConnectedRegisterUser.builder() + .mentorPost(mentorPost3) + .menteeUser(mentee_Two) + .state(NotConnectedRegisterUser.State.AWAIT) + .build(); + + //when + interestJPARepository.save(interest1); + interestJPARepository.save(interest2); + interestJPARepository.save(interest3); + userJPARepository.save(mentor); + userJPARepository.save(mentee_One); + userJPARepository.save(mentee_Two); + mentorPostJPARepostiory.save(mentorPost3); + userInterestJPARepository.save(userInterest1); + userInterestJPARepository.save(userInterest2); + userInterestJPARepository.save(userInterest3); + userInterestJPARepository.save(userInterest4); + userInterestJPARepository.save(userInterest5); + userInterestJPARepository.save(userInterest6); + contactJPARepository.save(menteeNotConnected1); + contactJPARepository.save(menteeNotConnected2); + } @Test - void test() throws Exception { + @DisplayName("updateMentorPostTest") + void updateMentorPostTest() + { + User writer = User.builder() + .email("anjdal6664@gmail.com") + .password("asdf1234!") + .firstName("Jin") + .lastName("Seung") + .country("Korea") + .age(21) + .role(Role.MENTOR) + .build(); + + MentorPostRequest.CreateDTO mentorPostRequest = new MentorPostRequest.CreateDTO(); + mentorPostRequest.setTitle("tittttttle"); + mentorPostRequest.setContent("content"); + + MentorPostRequest.CreateDTO mentorPostUpdated = new MentorPostRequest.CreateDTO(); + mentorPostUpdated.setTitle("updated!!!!"); + mentorPostUpdated.setContent("contenttt"); + + userJPARepository.save(writer); + mentorPostService.createMentorPost(mentorPostRequest, writer); + mentorPostService.updateMentorPost(mentorPostUpdated,1); + + MentorPost mentorPostFind = mentorPostJPARepostiory.findById(1); + Assertions.assertThat(1) + .isEqualTo(mentorPostFind.getId()); + Assertions.assertThat(mentorPostUpdated.getTitle()) + .isEqualTo(mentorPostFind.getTitle()); + Assertions.assertThat(mentorPostUpdated.getContent()) + .isEqualTo(mentorPostFind.getContent()); + } + - List responseDTOs = mentorPostService.findAllMentorPost(); + @Test + void mentorPostServiceTest() throws Exception { + MentorPostResponse.MentorPostDTO mentorPostFind = mentorPostService.findMentorPost(1); - String responseBody = om.writeValueAsString(responseDTOs); + String responseBody = om.writeValueAsString(mentorPostFind); System.out.println("test : " + responseBody); + } + + @WithUserDetails(value = "john@example.com") + @Test + public void CreateMentorPostTestMVC() throws Exception { + + MentorPostRequest.CreateDTO createDTO = new MentorPostRequest.CreateDTO(); + createDTO.setTitle("asfd"); + createDTO.setContent("afaffafa"); + String requestBody = om.writeValueAsString(createDTO); + + // when + ResultActions resultActions = mvc.perform( + post("/mentorings/post") + .content(requestBody) + .contentType(MediaType.APPLICATION_JSON_VALUE) + ); + + String responseBody = resultActions.andReturn().getResponse().getContentAsString(); + System.out.println("테스트 : " + responseBody); + + // verify + //resultActions.andExpect(jsonPath("$.success").value("true")); + //resultActions.andDo(MockMvcResultHandlers.print()).andDo(document); + } + + @WithUserDetails(value = "john@example.com") + @Test + public void GetMentorPostTestMVC() throws Exception { + + int id = 1; + + // when + ResultActions resultActions = mvc.perform( + get("/mentorings/post") + ); + + // console + String responseBody = resultActions.andReturn().getResponse().getContentAsString(); + System.out.println("테스트 : "+responseBody); } + }