Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1차] 윤시진 백엔드 과제 제출합니다. #5

Open
sijin1017 opened this issue Sep 18, 2024 · 0 comments
Open

[1차] 윤시진 백엔드 과제 제출합니다. #5

sijin1017 opened this issue Sep 18, 2024 · 0 comments

Comments

@sijin1017
Copy link

sijin1017 commented Sep 18, 2024

1. TDD 에 대한 이해

TDD란?

TDD 는 테스트 주도 개발로 기본적인 절차는 테스트 작성 —> 기능 구현 —> 리팩토링 단계로 이루어진다 !

**

  1. 테스트작성
    • Red 단계라고 하며 작성하려는 기능에 대하여 테스트 코드를 작성하는데, 아직 기능 코드가 없기 때문에 당연히 실패
  2. 기능 구현
    • Green 단계라고 하며, 테스트가 실패한 것을 앞서 확인하고 해당 테스트를 통과할 수 있는 최소한의 기능 코드를 작성
  3. 리팩토링
    • Refactor 단계라고 하며, 앞서 테스트가 통과하면 코드의 중복을 제거하거나 구조를 개선

TDD 의 장점

  • 버그가 발생하는 위치를 명확하게 알 수 있음
  • 유연하게 요구사항에 대처할 수 있음
  • 테스트 코드를 먼저 설계 후 작성하므로 코드가 간결해짐
  • 테스트 코드가 자연스럽게 문서화 역할을 하기때문에 문서화를 대체할 수 있음

TDD 의 단점

  • 생산성이 낮아짐 ( 원래 1번만 작성하는 코드를 2번 작성하는 것 )
  • 테스트를 작성하기 위한 초기 투자시간이 필요

TDD는 언제 필요할까? 왜 필요한가?

  1. 테스트는 코드가 의도대로 작동하는지 지속적으로 검증하는 역할을 하므로 버그가 발생할 경우 그 위치와 원인을 빠르게 파악가능하다
  2. 테스트 코드를 갖추면 리팩토링 할 때 코드가 기존 기능을 유지하는지 확인할 수 있기때문에 안전한 리팩토링이 가능하다
  3. 다른 개발자가 작성한 코드를 수정하거나 확장할 경우, 테스트 코드가 존재한다면 해당 코드가 어떻게 동작해야 하는지 알 수 있기에 협업 효율성을 높일 수 있다

2. 수강신청 서비스 구현

필수 구현 사항

  1. 회원 가입 및 로그인 기능 구현(1차 과제)
    • 학생 및 관리자 계정을 위한 회원 가입 및 로그인 기능
    • 로그인한 사용자만 수강신청 기능을 이용할 수 있도록 설정

https://github.com/sijin1017/9room-BE-1.git

3. 나의 이해와 의견

  1. 회원가입 기능에 대하여 테스트 케이스를 작성하였다. 중복된 이메일로 회원가입을 시도하는 경우, 정상적으로 회원가입이 이루어지도록 하였다.
@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Test
    public void testRegisterUser() {
        
        UserRegisterDto existingUser = new UserRegisterDto("[email protected]", "password", "STUDENT");
        userRepository.save(new User(existingUser.getEmail(), existingUser.getPassword(), existingUser.getRole()));

       
        UserRegisterDto newUser = new UserRegisterDto("[email protected]", "newpassword", "STUDENT");

       
        Assertions.assertThrows(ResponseStatusException.class, () -> {
            userService.registerUser(newUser);
        });

        
        UserRegisterDto uniqueUser = new UserRegisterDto("[email protected]", "password", "STUDENT");
        userService.registerUser(uniqueUser);

        
        User savedUser = userRepository.findByEmail("[email protected]").orElseThrow();
        Assertions.assertEquals("[email protected]", savedUser.getEmail());
    }
}
  1. 로그인 기능에서 유효성검증 + JWT 토큰 생성 로직을 추가하여 테스트를 통과하는 코드를 작성하였다.
@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenProvider jwtTokenProvider;

    public String loginUser(UserLoginDto loginDto) {
        User user = userRepository.findByEmail(loginDto.getEmail())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid credentials"));

        if (!passwordEncoder.matches(loginDto.getPassword(), user.getPassword())) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid credentials");
        }

        return jwtTokenProvider.createToken(user.getEmail(), user.getRole());
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant