반응형
Junit에서 redis를 @MockBean으로 만들어서 사용하던 중 에러가 발생했다.
사용한 코드는 다음과 같다.
@Test
@DisplayName("유효한 코드를 입력시 true를 반환")
fun checkValidCodeReturnTrue(){
//given
val email = "${UUID.randomUUID()}@test.com"
val code = UUID.randomUUID().toString()
//when
`when`(reactiveRedisTemplate.opsForValue().get("$redisKeyPrefix:$email"))
.thenReturn(Mono.just(code))
//then
StepVerifier.create(emailService.checkValidEmail(email, code))
.expectNext(true)
.verifyComplete()
}
Redis를 확인해보고 해당 인증번호가 있는지 확인하는 테스트코드이다.
여기서 다음과 같은 에러가 발생했다.
Cannot invoke "org.springframework.data.redis.core.ReactiveValueOperations.get(Object)" because the return value of "org.springframework.data.redis.core.ReactiveRedisTemplate.opsForValue()" is null
reactiveRedisTemplate은 opsForValue 메서드를 호출하면 ReactiveValueOperations를 반환하는데, 이 객체가 null이라는 것이다.
redis를 mocking하고 메서드를 호출 할 때는 바로 get을 호출하는 게 아니라, 그 중간에 ReactiveValueOperations도 Mocking하고 여기서 get을 호출해야 하는 것이다.
`when`(reactiveRedisTemplate.opsForValue())
.thenReturn(reactiveValueOperations)
`when`(reactiveValueOperations.get("$redisKeyPrefix:$email"))
.thenReturn(Mono.just(code))
이렇게 2단계로 when을 나누어주는 방법으로 테스트에 성공했다.
'토이 프로젝트' 카테고리의 다른 글
SSE를 사용한 앱 실행 중 알림 서비스 (0) | 2024.12.13 |
---|---|
AbstractGatewayFilterFactory 테스트하기 (1) | 2024.12.08 |
Kafka: The coordinator is not available. 에러 (0) | 2024.12.06 |
Reactive Kafka를 사용해 Email notification 서버에서 메일 보내기 (0) | 2024.11.28 |
WebFlux에서 RedissonReactive를 사용한 동시성 이슈 해결 (0) | 2024.11.17 |