테스트와 DI
2024. 7. 8. 13:30ㆍ토비의 스프링 6
수동 DI를 이용하는 테스트
테스트용 협력자(Collaborator) / 의존 오브젝트를 테스트 대상에 직접 주입하고 테스트
스프링 DI를 이용하는 테스트
테스트용 협력자(Collaborator) / 의존 오브젝트를 스프링의 구성 정보를 이용해서 지정하고 컨테이너로부터 테스트 대상을 가져와서 테스트
@ContextConfiguration
@Autowired
package tobyspring.hellospring.payment;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import tobyspring.hellospring.ObjectFactory;
import tobyspring.hellospring.TestObjectFactory;
import java.io.IOException;
import java.math.BigDecimal;
import static java.math.BigDecimal.valueOf;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestObjectFactory.class)
class PaymentServiceSpringTest {
@Autowired PaymentService paymentService;
@Test
void convertedAmount() throws IOException {
Payment payment = paymentService.prepare(1L, "USD", BigDecimal.TEN);
assertThat(payment.getExRate()).isEqualByComparingTo(valueOf(1_000));//BigDecimal은 isEqualTo로 비교하면 위험할 수 있다.
assertThat(payment.getConvertedAmount()).isEqualByComparingTo(valueOf(10_000));
}
// private static void getPayment() throws IOException {
// BeanFactory beanFactory = new AnnotationConfigApplicationContext(TestObjectFactory.class);
// PaymentService paymentService = beanFactory.getBean(PaymentService.class);
//
// Payment payment = paymentService.prepare(1L, "USD", BigDecimal.TEN);//테스트에서 exception이 터지면 테스트가 실패함
//
// assertThat(payment.getExRate()).isEqualByComparingTo(valueOf(1_000));//BigDecimal은 isEqualTo로 비교하면 위험할 수 있다.
// assertThat(payment.getConvertedAmount()).isEqualByComparingTo(valueOf(10_000));
// }
}'토비의 스프링 6' 카테고리의 다른 글
| 도메인 오브젝트 테스트 (0) | 2024.07.08 |
|---|---|
| 학습 테스트(Learning Test) (0) | 2024.07.08 |
| 테스트 (0) | 2024.07.06 |
| 의존성 역전 원칙(Dependency Inversion Principle) (0) | 2024.07.04 |
| DI와 디자인 패턴 (0) | 2024.07.04 |