포스트

Spring Boot Test - @InjectMock 사용하지 않고 Mock 객체를 사용하는 인스턴스 만들기

@Value 필드만 관리하는 SessionUserValue.java Component를 테스트시 임의의 값으로 직접 주입하기 위해 @InjectMocks 어노테이션을 사용하지 않고 직접 인스턴스를 생성해야 할 상황이 생겼다.

알아낸 방법을 기록 ✏️




@InjectMocks 어노테이션을 통해 생성하던 SessionUserService의 인스턴스를 직접 생성하여 사용하기 위해

  1. @InjectMocks 어노테이션을 삭제하고
  2. SessionUserService 인스턴스를 생성하기 전에
    MockitoAnnotations.openMocks(this) 코드를 먼저 작성하여 Mock 객체를 초기화 한 다음
  3. 마지막으로 SessionUserService 인스턴스를 생성하면서
    SessionUserValue Component의 인스턴스도 정의하여 직접 주입해준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@DisplayName("session user service")  
@ExtendWith(MockitoExtension.class)  
class SessionUserServiceTest {
	SessionUserService sessionUserService;  
	  
	@Mock SessionUserRepository sessionUserRepository;  
	@Mock RedisTemplate<String, String> redisTemplate;  
	  
	  
	@BeforeEach  
	void SessionUserServiceCreate() {  
	    MockitoAnnotations.openMocks(this);  
	    sessionUserService = new SessionUserService(  
	            sessionUserRepository,  
	            redisTemplate,  
	            new SessionUserValue(
		            "SESSION_ID:",  
		            "EMAIL:",  
		            "NICKNAME:",  
		            30
	            )  
	    );  
	}
}




참고한 사이트

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.