Spring

테스트 진행시 @Value (application.properties.yml) 값을 읽지 못할 때 (NullPointerException)

dodop 2022. 3. 4. 23:22

 

 

 

서비스 계층 테스트를 진행하려고 하는데 @Value값을 사용하는 경우

테스트 진행시 값이 없어 null pointer exception 이 발생하게 되었다. ( 프로퍼티 값이 로드되지 않기 때문!) 

( 추가로 테스트 진행시 Mockiito를 사용하지 않는다면 @TestPropertySource어노테이션을 이용해 테스트 프로퍼티 소스를 따로 분리할 수도 있다. )

 

 

 

 

기존 코드 
@Service
public class ProductService {

    @Value("${AWS_S3_BUCKET_URL}")
    private String AWS_S3_BUCKET_URL;
    //...
    
}

 

 

 

수정한 코드 
@Service
public class ProductService {
	
    private String bucketUrl;
    public ProductService( @Value("${AWS_S3_BUCKET_URL}") String bucketUrl) {
        this.bucketUrl = bucketUrl;
    }
    //...
}

해당 값을 생성자 주입 의존할때 @Value값을 통해서 실제 값을 넣어주도록 바꿔준다. 

 

 

 

 

테스트 코드 
@SpringBootTest
@ExtendWith(MockitoExtension.class)
@RunWith(SpringRunner.class)
@Transactional
class ProductServiceTests{

    @InjectMocks
    private ProductService productService = ("AwsValue");//다른 의존관계와 함께 넣어주면 됨

	//...

}

생성자 의존관계주입시 원하는 값을 넣어 테스트를 진행하면 된다. 

 

 

 

 

 

 

 

( 참고한 사이트 )

https://stackoverflow.com/questions/69018264/how-to-inject-value-constructor-parameter-using-mockito-annotation

 

How to inject @Value constructor parameter using Mockito annotation

I have a class: public class MyClass{ MyClass( @Value("${my.protocol}") String protocol, @Value("${my.host}") String host, @Value("$...

stackoverflow.com

https://tecoble.techcourse.co.kr/post/2020-09-21-application-properties/

 

프로퍼티 파일을 활용해 쉽게 실행 환경 분리하기

tecoble.techcourse.co.kr

https://stackoverflow.com/questions/69388544/unable-to-load-project-environment-variable-in-spring-boot-unit-test

 

Unable to load project environment variable in Spring Boot Unit Test

I have some variables defined in application-local.yml in my spring boot project and these variables are used in many of the services by using @Value annotation. Now while trying to unit test these

stackoverflow.com