package com.krylov.refound.service; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.krylov.refound.dto.PostResponse; import com.krylov.refound.entity.Post; import com.krylov.refound.entity.User; import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.exception.ApiException; import com.krylov.refound.mapper.PostMapper; import com.krylov.refound.repository.PostRepository; import com.krylov.refound.util.PostVisibility; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; /** GET /api/v1/users/{userId}/posts: что видит владелец и что — все остальные. */ @ExtendWith(MockitoExtension.class) class PostServiceUserPostsTest { @Mock private PostRepository postRepository; @Mock private PostMapper mapper; @Mock private UserService userService; @InjectMocks private PostService service; private final Pageable pageable = PageRequest.of(0, 20); @Test void ownerGetsAllOwnPostsIncludingUnpublished() { User owner = new User(); owner.setId(5L); when(userService.getCurrentUser()).thenReturn(owner); Post post = new Post(); when(postRepository.findByUserId(5L, pageable)).thenReturn(new PageImpl<>(List.of(post), pageable, 1)); PostResponse dto = new PostResponse(); when(mapper.toResponse(post)).thenReturn(dto); Page page = service.getPostsByUser(5L, pageable); assertThat(page.getContent()).containsExactly(dto); verify(postRepository, never()).findByUserIdAndStatusIn(any(), any(), any()); } @Test void othersGetOnlyPublishedPosts() { User someoneElse = new User(); someoneElse.setId(9L); when(userService.getCurrentUser()).thenReturn(someoneElse); when(postRepository.findByUserIdAndStatusIn(eq(5L), eq(PostVisibility.FEED_VISIBLE_STATUSES), eq(pageable))) .thenReturn(Page.empty(pageable)); Page page = service.getPostsByUser(5L, pageable); assertThat(page.getContent()).isEmpty(); verify(postRepository, never()).findByUserId(5L, pageable); } @Test void anonymousGetsOnlyPublishedPosts() { when(userService.getCurrentUser()) .thenThrow(new ApiException(ErrorCode.UNAUTHORIZED, "Unauthorized", HttpStatus.UNAUTHORIZED)); when(postRepository.findByUserIdAndStatusIn(eq(5L), eq(PostVisibility.FEED_VISIBLE_STATUSES), eq(pageable))) .thenReturn(Page.empty(pageable)); service.getPostsByUser(5L, pageable); verify(postRepository, never()).findByUserId(5L, pageable); } }