be_better

[Springboot] ImmutableCollections 에러 해결 본문

Springboot/Error 해결

[Springboot] ImmutableCollections 에러 해결

NiceTry 2024. 1. 3. 17:36

목차

    에러 내용

    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()
            )
        );