| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- ORM
- SpringSecurity
- spring
- 백엔드
- JWT
- restTemplate
- LinkedList
- Java
- error
- QueryDSL
- 연관관계
- spring boot
- 서버
- JPA
- 컴퓨터 공학
- SpringBoot
- 프로그래머스
- 백엔드스쿨
- 개발자
- actuator
- queue
- 컴퓨터 구조
- 자료구조
- 스프링부트
- TestCode
- 핵심가이드
- 제로베이스
- array
- 백준
- 백엔드공부
Archives
- Today
- Total
be_better
[Springboot] ImmutableCollections 에러 해결 본문
목차
에러 내용
User 권한 추가 테스트 코드 작성 중 ImmutableCollections 에러가 발생했다.
나의 경우 User 권한 roles를 Set 타입으로 지정하고 관리하고 있다.
mock으로 가상의 유저를 만들어주고 권한도 지정해준다.
Set<String> roleSet = Set.of("ROLE_VIEWER");
given(userRepository.findByUidAndDeletedAtNull(anyString()))
.willReturn(Optional.of(User.builder()
.uid("testId")
.roles(roleSet)
.build()
)
);
원인
원인은 roleSet을 선언해줄때 new HashSet<>() 이 아닌 Set.of() 로 지정해줬기 때문이다.
Set.of()를 사용하면 불변 컬렉션으로 만들라는 의미인데, 말그대로 불변 컬렉션은 삽입, 삭제, 수정 을 할 수 없게된다.
ImmutableCollections의 내부를 살펴보면
static UnsupportedOperationException uoe() { return new UnsupportedOperationException(); }
static abstract class AbstractImmutableCollection<E> extends AbstractCollection<E> {
// all mutating methods throw UnsupportedOperationException
@Override public boolean add(E e) { throw uoe(); }
@Override public boolean addAll(Collection<? extends E> c) { throw uoe(); }
@Override public void clear() { throw uoe(); }
@Override public boolean remove(Object o) { throw uoe(); }
@Override public boolean removeAll(Collection<?> c) { throw uoe(); }
@Override public boolean removeIf(Predicate<? super E> filter) { throw uoe(); }
@Override public boolean retainAll(Collection<?> c) { throw uoe(); }
}
add(), clear(), remove() 등 호출하면 UnsupportedOperationException() 예외를 내보내는것을 볼 수 있다.
해결
해결 방법은 간단하게 Set.of() 를 new HashSet<>() 으로 코드를 수정해주면 된다.
Set<String> roleSet = new HashSet<>(List.of("ROLE_VIEWER"));
given(userRepository.findByUidAndDeletedAtNull(anyString()))
.willReturn(Optional.of(User.builder()
.uid("testId")
.roles(roleSet)
.build()
)
);