인프런

컨트롤러를 소형 테스트로 만들기

date
Mar 2, 2025
slug
test-on-spring-with-architecture-5
status
Public
tags
테스트를 추가하고 싶은 개발자들의 오답노트
author
summary
Service 분리
type
Post
thumbnail
updatedAt
Mar 24, 2025 01:19 PM
category
인프런
CQRS
TDD

📝 강의 정리


[1]. Service 인터페이스 분리


유저 정보 조회 테스트

  • 특정 유저의 정보를 조회하는 컨트롤러 테스트를 진행할 때, UserService의 Read 메서드만 필요한 경우가 생긴다. 기존의 Service는 Read 메서드 이외에 여러 메서드가 있기에 필요치 않은 메서드도 override를 해주어야 하므로 이를 분리
    • AS-IS
      1. Test Code
      @Test void 유저_정보_조회() throw Exception { //given UserController userController = UserController .userService( new UserService() { @Override readMethod; @Override anotherMethod1; @Override anotherMethod2; }) .build();
       
      1. Service Interface
      public interface UserService { User getByEmail(String email); User getById(long id); User create(UserCreate userCreate); User update(long id, UserUpdate userUpdate); void login(long id); void verifyEmail(long id, String certificationCode); } public class UserServiceImpl implements UserService //
      TO-BE
      1. Test Code
      //TODO: 존재하지 않는 유저의 ID로 API 호출할 경우 404 응답을 받는다. @Test @DisplayName("존재하지 않는 유저의 ID로 API 호출할 경우 404 응답을 받는다") public void 존재하지_않는_유저의_ID로_API_호출할_경우_404_응답을_받는다() throws Exception { //values (100, 'rlawnsgh8395@naver.com', 'april2nd', 'seoul', 'aaaaa-aaaaaaaaaa-aaaaa-aaaaa', 'ACTIVE', 0); //given UserController userController = UserController.builder() .userReadService(new UserReadService() { @Override public User getByEmail(String email) { return null; } @Override public User getById(long id) { throw new ResourceNotFoundException("Users", id); } }) .build(); //when //then assertThatThrownBy(() -> { userController.getUserById(404L); }).isInstanceOf(ResourceNotFoundException.class); }
       
      1. Service Interface
      public interface AuthenticationService { void login(long id); void verifyEmail(long id, String certificationCode); } public interface UserCreateService { User create(UserCreate userCreate); } public interface UserReadService { User getByEmail(String email); User getById(long id); } public interface UserUpdateService { User update(long id, UserUpdate userUpdate); } public class UserServiceImpl implements UserReadService, UserCreateService, UserUpdateService, AuthenticationService
 

[2]. stub 벗어나기

  • 이전의 테스트 코드는 stub을 이용해 작성되었는데, 이를 개선해보자
    • → 어떤 메서드가 호출되면 이런 응답을 내려줘야한다 라는 코드 자체가 구현을 강제하는 것이 될 수 있으므로

TestContainer 작성

 
 

📎 출처