Error creating bean with name 'com.example.productorderservice.product.ProductApiTest': Injection of autowired dependencies failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.productorderservice.product.ProductApiTest': Injection of autowired dependencies failed
:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'local.server.port' in value "${local.server.port}"
스프링 부트 테스트 할 때 랜덤 포트를 설정해서 사용하려고 아래와 같이 ApiTest라는 클래스를 만들고 실제 API 테스트를 할 테스트 클래스에 extend를 한 뒤에 테스트 코드를 실행해 보니 아래와 같은 에러 파티가 일어났다.
일단 ApiTest 코드는 아래와 같다.
package com.example.productorderservice;
import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApiTest {
@LocalServerPort
private int port;
@BeforeEach
void setUp() {
RestAssured.port = port;
}
}
실제 테스트 코드를 작성한 코드는 아래와 같다.
package com.example.productorderservice.product;
import com.example.productorderservice.ApiTest;
import io.restassured.RestAssured;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@SpringBootTest
class ProductApiTest extends ApiTest {
@Test
void 상품등록() {
final AddProductRequest request = 상품등록요청_생성();
// API 요청
final ExtractableResponse<Response> response = RestAssured.given().log().all() // 요청을 보내는 로그를 남기겠다
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(request)
.when()
.post("/products")
.then()
.log().all().extract();
Assertions.assertThat(response.statusCode()).isEqualTo(HttpStatus.CREATED.value());
}
private static AddProductRequest 상품등록요청_생성() {
final String name = "상품명";
final int price = 1000;
final DiscountPolicy discountPolicy = DiscountPolicy.NONE;
return new AddProductRequest(name, price, discountPolicy);
}
}
여기서 문제가 무엇일까!
일단 나는 ProductApiTest 클래스에 ApiTest 클래스를 확장하려고 했다.
그래서 extends를 했고! 여기서 문제는 각 클래스에 @SpringBootTest 어노테이션을 사용한 것이 문제였다.
ApiTest에 @SpringBootTest를 사용했기 때문에 ProductApiTest에는 해당 어노테이션을 사용하지 않아도 되는 부분이였다.
그럼 ProductApiTest 클래스를 아래와 같이 @SpringBootTest 어노테이션을 제거하고 실행시키면 동작이 잘된다.
(참고로 테스트 코드 작성 중에 발견한 사항이라 테스트 성공하는 코드는 아니다)
class ProductApiTest extends ApiTest {
// 생략
}
생각보다 단순한 해결이였는데 이거 안보여서 해결하느라고 시간을 좀 썼다^___^
다음에 테스트 코드 작성할 때 주의해야겠다!