프로그래밍/Troubleshooting

[Junit] @SpyBean으로 @Cacheable 애노테이션이 붙은 메서드 mocking 시 문제 해결

저세상 개발자 2022. 4. 9. 18:26

문제

Mockito의 @SpyBean을 사용하여 @Cacheable annotation이 붙은 메서드를 mock 처리 하는 과정에서 다음과 같은 문제 발생

 

비지니스 로직

public class EHCacheService {

	...

	// mocking 하고자 하는 메서드
	@Cacheable(value = "foo", key = "#foo")
	public List<Something> getSomethingCache(long foo) {
		return otherService.getSomething(foo);
	}
}

테스트 코드

@SpringBootTest
public class EHCacheServiceTest {

	@SpyBean
	EHCacheService ehCacheService;

	@Test
	@DisplayName("getSomethingCache test")
	void testGetSomething() {
		...

        Something something = getSomething();
        doReturn(List.of(something)).when(ehCacheService).getSomethingCache(anyLong());

        ...
    }
}

발생한 에러

Invalid value type, expected : java.util.List but was : org.springframework.cache.support.NullValue

List 가 아니라 null이 반환되었다고 에러가 발생

 

문제 해결

관련 글: https://github.com/spring-projects/spring-framework/issues/24735

https://github.com/spring-projects/spring-framework/issues/24724

 

두 번째 링크를 확인해보면 아직 해결되지 않은 SpyBean 관련 버그로 보인다.

해결하기 위한 가장 간단한 방법은 @SpyBean annotation을 @MockBean 으로 고치는 것이다.